sys.settrace with a local function is about 40x slower than the same function at the top level
Created originally on Bitbucket by david_maciver_ (David MacIver)
The following code demonstrates the issue. A trivial tracing function which does nothing doesn't cause much of a slow down when defined at the top level, but when the same function is defined locally it takes much much longer:
#!python import sys import random import time def hash_str(s): h = 0 for c in s: h = (h * 31 + ord(c)) & (2 ** 64 - 1) return h random.seed(1) data = [ hex(random.getrandbits(1024)) for _ in range(500) ] def trace_global(frame, event, arg): return trace_global def trace_and_hash_global(d): sys.settrace(trace_global) hash_str(d) sys.settrace(None) def trace_and_hash_local(d): def trace_local(frame, event, arg): return trace_local sys.settrace(trace_local) hash_str(d) sys.settrace(None) if __name__ == '__main__': for ex in [trace_and_hash_global, trace_and_hash_local]: start = time.time() for d in data: ex(d) print(ex.__name__, time.time() - start)
For me this prints:
('trace_and_hash_global', 0.07121396064758301) ('trace_and_hash_local', 2.784956932067871)
This is running on pypy 2.6.0 on linux.