如何在 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)
))
我相信我过去已经做过这一切,但似乎无法将其挖掘出来..
最佳答案
timeit.Timer
正是这样做的。
from time import sleep
from timeit import Timer
print(Timer(lambda: sleep(5)).repeat(1, 1))
# [5.000540999999999]
repeat
只是对函数计时的一种方法,请阅读链接文档以了解其他可用方法。
关于python - 在 python 中执行任意*真实*代码块(不是字符串化版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56257458/