from datetime import datetime
from datetime import timedelta
start_time = datetime.now()
# returns the elapsed milliseconds since the start of the program
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return ms
(time.time_ns() + 500000) // 1000000 #rounding last digit (1ms digit)
或
time.time_ns() // 1000000 #flooring last digit (1ms digit)
这两种方法在其他方法中非常有效。
基准:
你可以在下面我自己的机器上看到一些不同方法的基准结果:
import time
t = time.perf_counter_ns()
for i in range(1000):
o = time.time_ns() // 1000000 #each 200 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = (time.time_ns() + 500000) // 1000000 #each 227 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = round(time.time_ns() / 1000000) #each 456 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = int(time.time_ns() / 1000000) #each 467 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = int(time.time()* 1000) #each 319 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)
t = time.perf_counter_ns()
for i in range(1000):
o = round(time.time()* 1000) #each 342 ns
t2 = time.perf_counter_ns()
print((t2 - t)//1000)```