1- import pytest
2- import tracemalloc
31from io import StringIO
42from time import sleep
53
64from memory_profiler import profile
7- import memory_profiler
85
9- tracemalloc .start ()
6+ try :
7+ import tracemalloc
8+ has_tracemalloc = True
9+ except ImportError :
10+ has_tracemalloc = False
11+
1012output = StringIO ()
1113
1214# allowable error in MB
1315EPSILON = 0.0001
1416
15- memory_profiler ._backend = 'tracemalloc'
16-
1717
18- @pytest .mark .parametrize ('test_input,expected' , [
19- (100 , 0.00012302398681640625 ),
20- (1000 , 0.0009813308715820312 ),
21- (10000 , 0.009564399719238281 ),
22- (100000 , 0.09539508819580078 ),
23- (1000000 , 0.9537019729614258 ),
24- (10000000 , 9.536770820617676 ),
25- (100000000 , 95.36745929718018 ),
26- ])
2718def test_memory_profiler (test_input , expected ):
2819 mem_prof (test_input )
2920 inc , dec = parse_mem_prof ()
3021 assert abs (inc - dec ) <= EPSILON , 'inc = {}, dec = {}, err = {}' .format (inc , dec , abs (inc - dec ))
3122 assert abs (inc - expected ) <= EPSILON , 'inc = {}, size = {}, err = {}' .format (inc , expected , abs (inc - expected ))
3223
3324
34- @profile (stream = output , precision = 6 )
25+ @profile (stream = output , precision = 6 , backend = 'tracemalloc' )
3526def mem_prof (n ):
3627 a = bytearray (n )
3728 del a
@@ -45,3 +36,17 @@ def f(s):
4536 return float (s .split ()[3 ])
4637
4738 return f (text [- 6 ]), - f (text [- 5 ])
39+
40+ if __name__ == '__main__' :
41+ if has_tracemalloc :
42+ tests = [
43+ (100 , 0.00012302398681640625 ),
44+ (1000 , 0.0009813308715820312 ),
45+ (10000 , 0.009564399719238281 ),
46+ (100000 , 0.09539508819580078 ),
47+ (1000000 , 0.9537019729614258 ),
48+ (10000000 , 9.536770820617676 ),
49+ (100000000 , 95.36745929718018 ),
50+ ]
51+ for test_input , expected in tests :
52+ test_memory_profiler (test_input , expected )
0 commit comments