How can a random code block be executed in python without resorting to string-ifying it . I am most likely not interested in using eval or exec .
So the use case would be to provide timing of a code block - but not requiring the hack of first converting the code block to a string:
def formatTimeDelta(td):
return '%d.%d' %(td.total_seconds() , int(td.microseconds/1000))
def timeit(tag, block):
def getNow(): return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
startt = datetime.datetime.now()
print('Starting %s at %s..' %(tag,getNow()))
block # Execute the code!
duration = formatTimeDelta(datetime.datetime.now() - startt)
print('Completed %s at %s with duration=%s secs' %(tag,getNow(), duration))
So then we would use something like:
Given a "random" code block
def waitsecs(nsecs):
import time
time.sleep(nsecs)
print('I slept %d secs..' %nsecs)
timeit('wait five secs', (
waitsecs(5)
))
I believe I had done all this in the past but can not seem to dig it up ..
timeit.Timeris for. For exampleprint(timeit.Timer(func_to_time).repeat(1, 1))timeit.Timer('for i in xrange(10): oct(i)', 'gc.enable()').timeit(). If you see a usage withTimerthat takes real code please do point it out.timeit.Timeralso accepts a callable, see my example