memory_profiling.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. """
  2. Script to try do detect any memory leaks that may be lurking in the C implementation of the PVector.
  3. """
  4. import inspect
  5. import sys
  6. import time
  7. import memory_profiler
  8. import vector_test
  9. from pyrsistent import pvector
  10. try:
  11. import pvectorc
  12. except ImportError:
  13. print("No C implementation of PVector available, terminating")
  14. sys.exit()
  15. PROFILING_DURATION = 2.0
  16. def run_function(fn):
  17. stop = time.time() + PROFILING_DURATION
  18. while time.time() < stop:
  19. fn(pvector)
  20. def detect_memory_leak(samples):
  21. # Do not allow a memory usage difference larger than 5% between the beginning and the end.
  22. # Skip the first samples to get rid of the build up period and the last sample since it seems
  23. # a little less precise
  24. return abs(1 - (sum(samples[5:8]) / sum(samples[-4:-1]))) > 0.05
  25. def profile_tests():
  26. test_functions = [fn for fn in inspect.getmembers(vector_test, inspect.isfunction)
  27. if fn[0].startswith('test_')]
  28. for name, fn in test_functions:
  29. # There are a couple of tests that are not run for the C implementation, skip those
  30. fn_args = inspect.getfullargspec(fn)[0]
  31. if 'pvector' in fn_args:
  32. print('Executing %s' % name)
  33. result = memory_profiler.memory_usage((run_function, (fn,), {}), interval=.1)
  34. assert not detect_memory_leak(result), (name, result)
  35. if __name__ == "__main__":
  36. profile_tests()