Two methods for calculating program running time in Python: datetime and time at the second/millisecond level

Two methods for calculating program running time in Python: datetime and time at the second/millisecond level

Simple and crude, let’s start with the code:

import datetime
import time

# 方法一:datetime.datetime.now() 时间和日期的结合 eg: 2021-10-15 14:19:27.875779
start_dt = datetime.datetime.now()
print("start_datetime:", start_dt)
time.sleep(2)
for i in range(10000):
    i += 1

end_dt = datetime.datetime.now()
print("end_datetime:", end_dt)
print("time cost:", (end_dt - start_dt).seconds, "s")


# -----------------------------------------------------------------
# 方法二:time.time() 获取当前时间戳
start_time = time.time()
print("start_time:", start_time)
time.sleep(2)
for i in range(10000):
    i += 1

end_time = time.time()
print("end_time:", end_time)
print("time cost:", end_time - start_time, "s")
print("time cost:", float(end_time - start_time) * 1000.0, "ms")

Output result:

start_datetime: 2021-10-15 14:19:27.875779
end_datetime: 2021-10-15 14:19:29.877386
time cost: 2 s
start_time: 1634278769.8773868
end_time: 1634278771.8848374
time cost: 2.007450580596924 s
time cost: 2007.4505805969238 ms

analyze:

datetime.datetime.now()It is a combination of time and date. For example: 2021-10-15 14:19:27.875779. When calculating the time difference, you need to call the .seconds or .microseconds method, as in the above code: (end_dt - start_dt).seconds, get the integer seconds (or microseconds)

datetime — basic date and time types

time.time()Used to get the current timestamp. Each timestamp is expressed as the amount of time that has passed since midnight (epoch) on January 1, 1970. The time interval is a floating point fraction in seconds. To convert to milliseconds, multiply by 1000. As in the above code:
print("time cost:", float(end_time - start_time) * 1000.0, "ms")

time and calendar modules in Python


I hope the above code is useful to everyone~

Guess you like

Origin blog.csdn.net/qq_39691492/article/details/120782415