如何在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)
))
我相信我過去曾經做過所有這些事情,但似乎無法将其挖掘出來。