How to calculate time difference using the time module in Python?

To calculate the time difference, you can use the time() function in the time module to get the current timestamp, and then perform the calculation. Here is an example code:

import time

# 获取当前时间的时间戳
start_time = time.time()

# 假设有一些需要执行的代码
for i in range(1000000):
    pass

# 获取执行完代码后的时间戳
end_time = time.time()

# 计算时间差
duration = end_time - start_time

# 打印时间差(以秒为单位)
print("代码执行时间:", duration, "秒")

In this example, we first use the time() function to get the current timestamp as the start time, then after executing some code, we use the time() function again to get the current timestamp as the end time, finally calculating the time difference and printing it out.

bannerAds