1. time.time() -> float
Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them.
单位为秒,返回浮点类型,返回公历计时时间戳。
import time
start = time.time() # 1657267196.3012242
#测试代码
end = time.time() # 1657267201.6171696
print('spend: %s second' % (end - start))
# spend: 5.315945386886597 second
2. time.perf_counter() -> float
Performance counter for benchmarking.
单位为妙,返回浮点类型时间戳,以程序执行为开始。
import time
start =time.clock() # 3.3892019
#测试代码
end = time.clock() # 8.7225603
print('spend: %s second' % (end - start))
# spend: 5.3333584 second
注:Python 3.8不支持time.clock()
。会报错module 'time' has no attribute 'clock'
。可以替换为此方法。
3. timeit.default_timer() -> float
单位为秒,返回浮点类型时间戳,貌似也是以程序执行为开始的。与2相比来自的标准库不一样,其他区别未考究,不详。
import timeit
start = timeit.default_timer() # start: 3.3247171
#测试代码
end = timeit.default_timer() # end: 8.5791582
print('spend: %s second' % (end - start))
# spend: 5.2544411 second
补充:
timeit.default_timer()
The default timer, which is always time.perf_counter().
所以来看和2应该是一样的。
4. datetime.datetime.now() -> Self
Construct a datetime from time.time() and optional time zone info.
返回<class 'datetime.datetime'>
类型时间戳,格式见示例。
import datetime
start=datetime.datetime.now() # 2022-07-08 17:04:58.614047
#测试代码
end=datetime.datetime.now() # 2022-07-08 17:05:03.860025
print('spend: %s Seconds'%(end-start))
# spend: 0:00:05.245978 second
datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])