如何在python中执行随机代码块而又不求其字符串化。我很可能对使用eval或exec不感兴趣。
因此,用例将是提供代码块的计时-但不需要先将代码块转换为字符串的技巧:
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))
因此,我们将使用类似于:
给定一个“随机”代码块
def waitsecs(nsecs):
import time
time.sleep(nsecs)
print('I slept %d secs..' %nsecs)
timeit('wait five secs', (
waitsecs(5)
))
我相信我过去曾经做过所有这些事情,但似乎无法将其挖掘出来。