与时间模块在python是可能测量经过的时间?如果是,我该怎么做?
我需要这样做,以便如果光标在小部件中停留了一段时间,就会发生一个事件。
与时间模块在python是可能测量经过的时间?如果是,我该怎么做?
我需要这样做,以便如果光标在小部件中停留了一段时间,就会发生一个事件。
当前回答
在编程中,主要有两种测量时间的方法,结果不同:
>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001 # took 0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075 # took 10 seconds and a bit
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this. Use time.process_time() Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time. Use time.perf_counter() time.time() also measures wall-clock time but can be reset, so you could go back in time time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
其他回答
在编程中,主要有两种测量时间的方法,结果不同:
>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001 # took 0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075 # took 10 seconds and a bit
Processor Time: This is how long this specific process spends actively being executed on the CPU. Sleep, waiting for a web request, or time when only other processes are executed will not contribute to this. Use time.process_time() Wall-Clock Time: This refers to how much time has passed "on a clock hanging on the wall", i.e. outside real time. Use time.perf_counter() time.time() also measures wall-clock time but can be reset, so you could go back in time time.monotonic() cannot be reset (monotonic = only goes forward) but has lower precision than time.perf_counter()
这是一个更新的Vadim Shender的聪明的代码与表格输出:
import collections
import time
from functools import wraps
PROF_DATA = collections.defaultdict(list)
def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):
start_time = time.time()
ret = fn(*args, **kwargs)
elapsed_time = time.time() - start_time
PROF_DATA[fn.__name__].append(elapsed_time)
return ret
return with_profiling
Metrics = collections.namedtuple("Metrics", "sum_time num_calls min_time max_time avg_time fname")
def print_profile_data():
results = []
for fname, elapsed_times in PROF_DATA.items():
num_calls = len(elapsed_times)
min_time = min(elapsed_times)
max_time = max(elapsed_times)
sum_time = sum(elapsed_times)
avg_time = sum_time / num_calls
metrics = Metrics(sum_time, num_calls, min_time, max_time, avg_time, fname)
results.append(metrics)
total_time = sum([m.sum_time for m in results])
print("\t".join(["Percent", "Sum", "Calls", "Min", "Max", "Mean", "Function"]))
for m in sorted(results, reverse=True):
print("%.1f\t%.3f\t%d\t%.3f\t%.3f\t%.3f\t%s" % (100 * m.sum_time / total_time, m.sum_time, m.num_calls, m.min_time, m.max_time, m.avg_time, m.fname))
print("%.3f Total Time" % total_time)
另一种计算时间的好方法是使用with python结构。
With结构会自动调用__enter__和__exit__方法,这正是我们为事情计时所需要的。
让我们创建一个Timer类。
from time import time
class Timer():
def __init__(self, message):
self.message = message
def __enter__(self):
self.start = time()
return None # could return anything, to be used like this: with Timer("Message") as value:
def __exit__(self, type, value, traceback):
elapsed_time = (time() - self.start) * 1000
print(self.message.format(elapsed_time))
然后,你可以像这样使用Timer类:
with Timer("Elapsed time to compute some prime numbers: {}ms"):
primes = []
for x in range(2, 500):
if not any(x % p == 0 for p in primes):
primes.append(x)
print("Primes: {}".format(primes))
结果如下:
Primes:[2、3、5、7、11、13、17、19、23、29、31、37、41、43、47、53、59、61、67, 71、73、79、83、89、97、101、103、107、109、113、127、131、137、139、149、151、 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241、251、257、263、269、271、277、281、283、293、307、311、313、317、331、337、 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439、443、449、457、461、463、467、479、487、491、499)
计算一些质数所需的时间:5.01704216003418ms
start_time = time.time()
# your code
elapsed_time = time.time() - start_time
你也可以编写简单的装饰器来简化各种函数执行时间的测量:
import time
from functools import wraps
PROF_DATA = {}
def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):
start_time = time.time()
ret = fn(*args, **kwargs)
elapsed_time = time.time() - start_time
if fn.__name__ not in PROF_DATA:
PROF_DATA[fn.__name__] = [0, []]
PROF_DATA[fn.__name__][0] += 1
PROF_DATA[fn.__name__][1].append(elapsed_time)
return ret
return with_profiling
def print_prof_data():
for fname, data in PROF_DATA.items():
max_time = max(data[1])
avg_time = sum(data[1]) / len(data[1])
print "Function %s called %d times. " % (fname, data[0]),
print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)
def clear_prof_data():
global PROF_DATA
PROF_DATA = {}
用法:
@profile
def your_function(...):
...
您可以同时分析多个函数。然后要打印测量值,只需调用print_prof_data():
对于想要更好格式的用户,
import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
将打印出来,持续2秒:
'00:00:02'
在7分1秒内:
'00:07:01'
注意,gmtime的最小时间单位是秒。如果您需要微秒,请考虑以下内容:
import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds)
strftime文档