File: memory.py

package info (click to toggle)
ujson 5.11.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,148 kB
  • sloc: ansic: 2,789; python: 1,510; cpp: 50; makefile: 43; sh: 12
file content (45 lines) | stat: -rw-r--r-- 1,019 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import gc
import sys
import tracemalloc

# exec the first argument to get func() and n
exec_globals = {}
exec(sys.argv[1], exec_globals)
func = exec_globals["func"]
n = int(sys.argv[2]) if sys.argv[2:] else 1

# Pre-run once
try:
    func()
except Exception:
    pass

# Create filter to only report leaks on the 'tracemalloc: measure' line below
filters = []
with open(__file__) as fp:
    for i, line in enumerate(fp, start=1):
        if "tracemalloc: measure" in line:
            filters.append(tracemalloc.Filter(True, __file__, i))

# Clean up and take a snapshot
tracemalloc.start()
gc.collect()
before = tracemalloc.take_snapshot().filter_traces(filters)

# Run
for i in range(n):
    try:
        func()  # tracemalloc: measure
    except Exception:
        pass

# Clean up and second snapshot
gc.collect()
after = tracemalloc.take_snapshot().filter_traces(filters)

# Check that nothing got leaked
diff = after.compare_to(before, "lineno")
if diff:
    for stat in diff:
        print(stat)
    sys.exit(1)