我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
我想测量执行一个函数所花费的时间。我没时间工作:
import timeit
start = timeit.timeit()
print("hello")
end = timeit.timeit()
print(end - start)
当前回答
对于Python 3
如果使用时间模块,则可以获取当前时间戳,然后执行代码,然后再次获取时间戳。现在,所用时间将是第一个时间戳减去第二个时间戳:
import time
first_stamp = int(round(time.time() * 1000))
# YOUR CODE GOES HERE
time.sleep(5)
second_stamp = int(round(time.time() * 1000))
# Calculate the time taken in milliseconds
time_taken = second_stamp - first_stamp
# To get time in seconds:
time_taken_seconds = round(time_taken / 1000)
print(f'{time_taken_seconds} seconds or {time_taken} milliseconds')
其他回答
这种独特的基于类的方法提供了可打印的字符串表示、可自定义的舍入,以及以字符串或浮点形式方便地访问经过的时间。它是用Python 3.7开发的。
import datetime
import timeit
class Timer:
"""Measure time used."""
# Ref: https://stackoverflow.com/a/57931660/
def __init__(self, round_ndigits: int = 0):
self._round_ndigits = round_ndigits
self._start_time = timeit.default_timer()
def __call__(self) -> float:
return timeit.default_timer() - self._start_time
def __str__(self) -> str:
return str(datetime.timedelta(seconds=round(self(), self._round_ndigits)))
用法:
# Setup timer
>>> timer = Timer()
# Access as a string
>>> print(f'Time elapsed is {timer}.')
Time elapsed is 0:00:03.
>>> print(f'Time elapsed is {timer}.')
Time elapsed is 0:00:04.
# Access as a float
>>> timer()
6.841332235
>>> timer()
7.970274425
在python3上:
from time import sleep, perf_counter as pc
t0 = pc()
sleep(1)
print(pc()-t0)
优雅而短小。
如何测量两次操作之间的时间。比较两次操作的时间。
import time
b = (123*321)*123
t1 = time.time()
c = ((9999^123)*321)^123
t2 = time.time()
print(t2-t1)
7.987022399902344e-05
对于Python 3
如果使用时间模块,则可以获取当前时间戳,然后执行代码,然后再次获取时间戳。现在,所用时间将是第一个时间戳减去第二个时间戳:
import time
first_stamp = int(round(time.time() * 1000))
# YOUR CODE GOES HERE
time.sleep(5)
second_stamp = int(round(time.time() * 1000))
# Calculate the time taken in milliseconds
time_taken = second_stamp - first_stamp
# To get time in seconds:
time_taken_seconds = round(time_taken / 1000)
print(f'{time_taken_seconds} seconds or {time_taken} milliseconds')
您可以使用Benchmark Timer(免责声明:我是作者):
基准计时器使用BenchmarkTimer类来测量执行某段代码所需的时间。这比内置的timeit函数具有更大的灵活性,并且与其他代码在相同的范围内运行。安装pip安装git+https://github.com/michaelitvin/benchmark-timer.git@main#egg=基准计时器用法单次迭代示例从benchmark_timer导入BenchmarkTimer导入时间使用BenchmarkTimer(name=“MySimpleCode”)作为tm,tm.single_ieration():睡眠时间(.3)输出:正在对标MySimpleCode。。。MySimpleCode基准:n_iters=1 avg=0.300881s std=0.000000s range=[0.3000881s ~ 0.300881s]多次迭代示例从benchmark_timer导入BenchmarkTimer导入时间使用BenchmarkTimer(name=“MyTimedCode”,print_iters=True)作为tm:对于tm迭代中的timing_iteration(n=5,预热=2):定时重复:睡眠时间(.1)打印(“\n===============\n”)print(“定时列表:”,列表(tm.timenings.values()))输出:正在对标MyTimedCode。。。[MyTimedCode]iter=0耗时0.099755s(预热)[MyTimedCode]iter=1耗时0.100476秒(预热)[MyTimedCode]iter=2耗时0.100189秒[MyTimedCode]iter=3耗时0.099900s[MyTimedCode]iter=4耗时0.100888秒MyTimedCode基准:n_iters=3 avg=0.100326s std=0.000414s range=[0.099900s ~ 0.100888s]===================时间列表:[0.1001885000000001,0.09990049999999995,0.10088760000000008]