I created two functions: one empty and one that opens a file and writes a line and closes it. I ran once without scope-guard, and once with for each. Short unscoped (us): 17.485010669 Short and scoped (us): 72.8106022384 Long unscoped (ms): 19.7690964161 Long and scoped (ms): 20.380344323 Here is the code with the tests: import sys def ScopeGuarded(func): return lambda *args, **kwargs: ScopeGuardian(func, *args, **kwargs) _funcStack = [] def ScopeGuardian(func, *args, **kwargs): try: scopedObjs = [] _funcStack.append(scopedObjs) func(*args, **kwargs) finally: _funcStack.pop() if scopedObjs != []: scopedObjs.reverse() # destroy in reverse order from creation for obj in scopedObjs: obj.finalizeMaster() def testTimingShort(scoped=False): def fastFun(): pass if scoped: fastFun = ScopeGuarded(fastFun) fastFun() def testTimingLong(scoped=False): def slowFun(): ff = file('asdfaf','w') ff.write('asdfaf') ff.close() if scoped: slowFun = ScopeGuarded(slowFun) slowFun() def testTiming(): from timeit import Timer tts = Timer('testTimingShort()', 'from __main__ import testTimingShort') ttss = Timer('testTimingShort(True)', 'from __main__ import testTimingShort') ttl = Timer('testTimingLong()', 'from __main__ import testTimingLong') ttls = Timer('testTimingLong(True)', 'from __main__ import testTimingLong') tms = tts.timeit(10000)*100 print "Short unscoped (us): ", tms tmss = ttss.timeit(10000)*100 print "Short and scoped (us):", tmss tml = ttl.timeit(100)*10 print "Long unscoped (ms): ", tml tmls = ttls.timeit(100)*10 print "Long and scoped (ms): ", tmls print "For long, scoped takes %s%% longer than unscoped" % ((tmls/tml-1)*100) if __name__ == '__main__': testTiming()
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4