与时间模块在python是可能测量经过的时间?如果是,我该怎么做?
我需要这样做,以便如果光标在小部件中停留了一段时间,就会发生一个事件。
与时间模块在python是可能测量经过的时间?如果是,我该怎么做?
我需要这样做,以便如果光标在小部件中停留了一段时间,就会发生一个事件。
当前回答
Time.time()就可以了。
import time
start = time.time()
# run your code
end = time.time()
elapsed = end - start
你可能想看看这个问题,但我认为没有必要。
其他回答
对于想要更好格式的用户,
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文档
您需要导入时间,然后使用time.time()方法来了解当前时间。
import time
start_time=time.time() #taking current time as starting time
#here your code
elapsed_time=time.time()-start_time #again taking current time - starting time
瓦迪姆·申德的反应很棒。你也可以使用一个简单的装饰器,如下所示:
import datetime
def calc_timing(original_function):
def new_function(*args,**kwargs):
start = datetime.datetime.now()
x = original_function(*args,**kwargs)
elapsed = datetime.datetime.now()
print("Elapsed Time = {0}".format(elapsed-start))
return x
return new_function()
@calc_timing
def a_func(*variables):
print("do something big!")
Time.time()就可以了。
import time
start = time.time()
# run your code
end = time.time()
elapsed = end - start
你可能想看看这个问题,但我认为没有必要。
在编程中,主要有两种测量时间的方法,结果不同:
>>> 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()