On Fri, 22 Jul 2022 at 09:00, Barry <ba...@barrys-emacs.org> wrote: > With code as complex as python’s there will be memory allocations that occur that will not be directly related to the python code you test. > > To put it another way there is noise in your memory allocation signal. > > Usually the signal of a memory leak is very clear, as you noticed. > > For rare leaks I would use a tool like valgrind.
Thank you all, but I needed a simple decorator to automatize the memory leak (and segfault) tests. I think that this version is good enough, I hope that can be useful to someone: def trace(iterations=100): def decorator(func): def wrapper(): print( f"Loops: {iterations} - Evaluating: {func.__name__}", flush=True ) tracemalloc.start() snapshot1 = tracemalloc.take_snapshot().filter_traces( (tracemalloc.Filter(True, __file__), ) ) for i in range(iterations): func() gc.collect() snapshot2 = tracemalloc.take_snapshot().filter_traces( (tracemalloc.Filter(True, __file__), ) ) top_stats = snapshot2.compare_to(snapshot1, 'lineno') tracemalloc.stop() for stat in top_stats: if stat.count_diff * 100 > iterations: raise ValueError(f"stat: {stat}") return wrapper return decorator If the decorated function fails, you can try to raise the iterations parameter. I found that in my cases sometimes I needed a value of 200 or 300 -- https://mail.python.org/mailman/listinfo/python-list