gpt4 book ai didi

python - 在 python 中执行任意*真实*代码块(不是字符串化版本)

转载 作者:太空宇宙 更新时间:2023-11-04 09:29:29 27 4
gpt4 key购买 nike

如何在 python 中执行随机代码块而不诉诸字符串化。我很可能对使用evalexec 感兴趣。

因此用例是提供代码块的计时 - 但不需要首先将代码块转换为字符串的技巧:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com