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



如何在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只是对函数进行计时的一种方式,请阅读链接的文档以了解其他可用方法。

我发现最简单的方法是使用 ipython 或 Jupyter notebook 中的魔术命令%timeit。如果需要,可以指定重复次数和循环次数:

$ ipython                                                                                                           
In [1]: import time
In [2]: %timeit -n1 -r1 time.sleep(5)
5 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
In [3]: %timeit [i**2 for i in range(10000)]
8.12 ms ± 14.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

您不需要任何 lambda、任何定义的函数或任何字符串化代码。

你可以向函数发送 callabletimeit.timeit()前提是它没有属性。如果它有任何属性,则应使用安装代码。

timeit.timeit()函数具有设置属性。您可以在对象开始工作之前发送代码(但仍是字符串化timeitTimer以"评估"它。下面是示例:

import timeit
s = """
import math
def waka(number):
return math.sqrt(number)
"""
timeit.timeit('waka(100)', setup=s)

这是timeit.timeit()的工作原理:

使用给定的语句、设置代码和计时器函数创建一个 Timer 实例,并通过数字执行运行其 timeit() 方法。可选的 globals 参数指定要在其中执行代码的命名空间。

使用装饰器,例如: @timeit装饰器:

def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
if 'log_time' in kw:
name = kw.get('log_name', method.__name__.upper())
kw['log_time'][name] = int((te - ts) * 1000)
else:
print '%r  %2.2f ms' % 
(method.__name__, (te - ts) * 1000)
return result
return timed

将装饰器添加到方法中:

@timeit
def get_all_employee_details(**kwargs):
print 'employee details'

取自: https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d

最新更新