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()
Welcome to the profile statistics browser.timeStats.profile% stats hello<timestamp> timeStats.profile
224 function calls in 6.014 seconds
Random listing order was usedList 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 usedList 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)
with elapsed_timer() as elapsed:# some lengthy codeprint( "midpoint at %.2f seconds" % elapsed() ) # time so far# other lengthy code
print( "all done at %.2f seconds" % elapsed() )
import time, datetime
start = time.clock()
def num_multi1(max):result = 0for num in range(0, 1000):if (num % 3 == 0 or num % 5 == 0):result += num
print "Sum is %d " % result
num_multi1(1000)
end = time.clock()value = end - starttimestamp = datetime.datetime.fromtimestamp(value)print timestamp.strftime('%Y-%m-%d %H:%M:%S')
import timing
@timing.MeasureTimedef MyBigFunc():#do something time consumingfor i in range(10000):print(i)
timing.print_all_timings()
如果你想对代码部分进行计时,那么只需将其放在with块中:
import timing
#somewhere in my code
with timing.MeasureBlockTime("MyBlock"):#do something time consumingfor i in range(10000):print(i)
# rest of my code
timing.print_all_timings()
优点:
有几个半支持的版本,所以我想指出一些亮点:
由于前面描述的原因,使用timeit的计时器而不是time.time。
如果需要,您可以在计时期间禁用GC。
装饰器接受具有命名或未命名参数的函数。
能够在块计时中禁用打印(使用with timing.MeasureBlockTime() as t,然后使用t.elapsed)。
>> from pytictoc import TicToc>> t = TicToc() # create TicToc instance>> t.tic() # Start timer>> # do something>> t.toc() # Print elapsed timeElapsed time is 2.612231 seconds.
与传统方式相比:
>> from time import time>> t1 = time()>> # do something>> t2 = time()>> elapsed = t2 - t1>> print('Elapsed time is %f seconds.' % elapsed)Elapsed time is 2.612231 seconds.
# 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
from functools import wrapsfrom time import perf_counterfrom typing import Any, Callable, Optional, TypeVar, cast
F = TypeVar("F", bound=Callable[..., Any])
def timer(prefix: Optional[str] = None, precision: int = 6) -> Callable[[F], F]:"""Use as a decorator to time the execution of any function.
Args:prefix: String to print before the time taken.Default is the name of the function.precision: How many decimals to include in the seconds value.
Examples:>>> @timer()... def foo(x):... return x>>> foo(123)foo: 0.000...s123>>> @timer("Time taken: ", 2)... def foo(x):... return x>>> foo(123)Time taken: 0.00s123
"""def decorator(func: F) -> F:@wraps(func)def wrapper(*args: Any, **kwargs: Any) -> Any:nonlocal prefixprefix = prefix if prefix is not None else f"{func.__name__}: "start = perf_counter()result = func(*args, **kwargs)end = perf_counter()print(f"{prefix}{end - start:.{precision}f}s")return resultreturn cast(F, wrapper)return decorator
示例用法:
from timer import timer
@timer(precision=9)def takes_long(x: int) -> bool:return x in (i for i in range(x + 1))
result = takes_long(10**8)print(result)
import time
first_stamp = int(round(time.time() * 1000))
# YOUR CODE GOES HEREtime.sleep(5)
second_stamp = int(round(time.time() * 1000))
# Calculate the time taken in millisecondstime_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')
from benchmark_timer import BenchmarkTimerimport time
with BenchmarkTimer(name="MyTimedCode", print_iters=True) as tm:for timing_iteration in tm.iterations(n=5, warmup=2):with timing_iteration:time.sleep(.1)
print("\n===================\n")print("List of timings: ", list(tm.timings.values()))
输出:
Benchmarking MyTimedCode...[MyTimedCode] iter=0 took 0.099755s (warmup)[MyTimedCode] iter=1 took 0.100476s (warmup)[MyTimedCode] iter=2 took 0.100189s[MyTimedCode] iter=3 took 0.099900s[MyTimedCode] iter=4 took 0.100888sMyTimedCode benchmark: n_iters=3 avg=0.100326s std=0.000414s range=[0.099900s~0.100888s]
===================
List of timings: [0.10018850000000001, 0.09990049999999995, 0.10088760000000008]