| 1 |
import math |
| 2 |
from rpython.rlib.rarithmetic import r_int64 |
| 3 |
from rpython.rlib.debug import debug_start, debug_print, debug_stop |
| 4 |
from rpython.rlib.objectmodel import we_are_translated |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
class MemoryManager(object): |
| 24 |
|
| 25 |
def __init__(self): |
| 26 |
self.check_frequency = -1 |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
self.current_generation = r_int64(1) |
| 39 |
self.next_check = r_int64(-1) |
| 40 |
self.alive_loops = {} |
| 41 |
|
| 42 |
def set_max_age(self, max_age, check_frequency=0): |
| 43 |
if max_age <= 0: |
| 44 |
self.next_check = r_int64(-1) |
| 45 |
else: |
| 46 |
self.max_age = max_age |
| 47 |
if check_frequency <= 0: |
| 48 |
check_frequency = int(math.sqrt(max_age)) |
| 49 |
self.check_frequency = check_frequency |
| 50 |
self.next_check = self.current_generation + 1 |
| 51 |
|
| 52 |
def next_generation(self): |
| 53 |
self.current_generation += 1 |
| 54 |
if self.current_generation == self.next_check: |
| 55 |
self._kill_old_loops_now() |
| 56 |
self.next_check = self.current_generation + self.check_frequency |
| 57 |
|
| 58 |
def keep_loop_alive(self, looptoken): |
| 59 |
if looptoken.generation != self.current_generation: |
| 60 |
looptoken.generation = self.current_generation |
| 61 |
self.alive_loops[looptoken] = None |
| 62 |
|
| 63 |
def _kill_old_loops_now(self): |
| 64 |
debug_start("jit-mem-collect") |
| 65 |
oldtotal = len(self.alive_loops) |
| 66 |
|
| 67 |
debug_print("Current generation:", self.current_generation) |
| 68 |
debug_print("Loop tokens before:", oldtotal) |
| 69 |
max_generation = self.current_generation - (self.max_age-1) |
| 70 |
for looptoken in self.alive_loops.keys(): |
| 71 |
if (0 <= looptoken.generation < max_generation or |
| 72 |
looptoken.invalidated): |
| 73 |
del self.alive_loops[looptoken] |
| 74 |
newtotal = len(self.alive_loops) |
| 75 |
debug_print("Loop tokens freed: ", oldtotal - newtotal) |
| 76 |
debug_print("Loop tokens left: ", newtotal) |
| 77 |
|
| 78 |
if not we_are_translated() and oldtotal != newtotal: |
| 79 |
looptoken = None |
| 80 |
from rpython.rlib import rgc |
| 81 |
|
| 82 |
rgc.collect(); rgc.collect(); rgc.collect() |
| 83 |
debug_stop("jit-mem-collect") |
| 84 |
|
| 85 |
def release_all_loops(self): |
| 86 |
debug_start("jit-mem-releaseall") |
| 87 |
debug_print("Loop tokens cleared:", len(self.alive_loops)) |
| 88 |
self.alive_loops.clear() |
| 89 |
debug_stop("jit-mem-releaseall") |