我想测量执行一个函数所花费的时间。我没时间工作:

import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)

当前回答

如何测量两次操作之间的时间。比较两次操作的时间。

import time

b = (123*321)*123
t1 = time.time()

c = ((9999^123)*321)^123
t2 = time.time()

print(t2-t1)

7.987022399902344e-05

其他回答

使用探查器模块。它提供了非常详细的概况。

import profile
profile.run('main()')

它输出类似于:

          5 function calls in 0.047 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :0(exec)
        1    0.047    0.047    0.047    0.047 :0(setprofile)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        0    0.000             0.000          profile:0(profiler)
        1    0.000    0.000    0.047    0.047 profile:0(main())
        1    0.000    0.000    0.000    0.000 two_sum.py:2(twoSum)

我发现它很有启发性。

作为lambda,获取经过的时间和时间戳:

import datetime
t_set = lambda: datetime.datetime.now().astimezone().replace(microsecond=0)
t_diff = lambda t: str(t_set() - t)
t_stamp = lambda t=None: str(t) if t else str(t_set())

在实践中:

>>> 
>>> t_set()
datetime.datetime(2021, 3, 21, 1, 25, 17, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=61200), 'PDT'))
>>> t = t_set()
>>> t_diff(t)
'0:00:14'
>>> t_diff(t)
'0:00:23'
>>> t_stamp()
'2021-03-21 01:25:57-07:00'
>>> t_stamp(t)
'2021-03-21 01:25:22-07:00'
>>> 

python cProfile和pstats模块为测量某些函数的时间提供了强大的支持,而无需在现有函数周围添加任何代码。

例如,如果您有python脚本timeFunctions.py:

import time

def hello():
    print "Hello :)"
    time.sleep(0.1)

def thankyou():
    print "Thank you!"
    time.sleep(0.05)

for idx in range(10):
    hello()

for idx in range(100):
    thankyou()

要运行探查器并生成文件的统计信息,只需运行:

python -m cProfile -o timeStats.profile timeFunctions.py

这是在使用cProfile模块来评测timeFunctions.py中的所有函数,并在timeStats.profile文件中收集统计信息。注意,我们不必向现有模块(timeFunctions.py)添加任何代码,这可以通过任何模块来完成。

一旦有了stats文件,就可以按如下方式运行pstats模块:

python -m pstats timeStats.profile

这将运行交互式统计浏览器,它为您提供了许多不错的功能。对于您的特定用例,您可以只检查函数的统计信息。在我们的示例中,检查两个函数的统计信息显示如下:

Welcome to the profile statistics browser.
timeStats.profile% stats hello
<timestamp>    timeStats.profile

         224 function calls in 6.014 seconds

   Random listing order was used
   List reduced from 6 to 1 due to restriction <'hello'>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       10    0.000    0.000    1.001    0.100 timeFunctions.py:3(hello)

timeStats.profile% stats thankyou
<timestamp>    timeStats.profile

         224 function calls in 6.014 seconds

   Random listing order was used
   List reduced from 6 to 1 due to restriction <'thankyou'>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
      100    0.002    0.000    5.012    0.050 timeFunctions.py:7(thankyou)

这个假例子做不了什么,但给了你一个可以做什么的想法。这种方法最好的一点是,我不必编辑任何现有代码来获取这些数字,并且显然有助于分析。

这是一种很晚的反应,但也许对某人来说是有目的的。这是一种我认为非常干净的方法。

import time

def timed(fun, *args):
    s = time.time()
    r = fun(*args)
    print('{} execution took {} seconds.'.format(fun.__name__, time.time()-s))
    return(r)

timed(print, "Hello")

请记住,“print”是Python 3中的函数,而不是Python 2.7中的函数。但是,它可以与任何其他功能一起使用。干杯

我更喜欢这个。timeit医生太令人困惑了。

from datetime import datetime 

start_time = datetime.now() 

# INSERT YOUR CODE 

time_elapsed = datetime.now() - start_time 

print('Time elapsed (hh:mm:ss.ms) {}'.format(time_elapsed))

注意,这里没有进行任何格式化,我只是在打印输出中写入hh:mm:ss,以便可以解释time_elapsed