Python 如何获取代码的执行时间?
我想计算各种语言的代码的执行时间,比如java、python、javascript。如何获取这些代码的执行时间。python包或任何其他包中是否有任何工具可以通过传递文件(java或python的任何文件)路径来计算执行时间。请分享你的建议 我知道在python代码中使用时间模块可以获得执行时间。如何在python中执行Javascript和java代码,并在公共函数中获得执行时间 我试过下面的方法Python 如何获取代码的执行时间?,python,performance-testing,execution-time,Python,Performance Testing,Execution Time,我想计算各种语言的代码的执行时间,比如java、python、javascript。如何获取这些代码的执行时间。python包或任何其他包中是否有任何工具可以通过传递文件(java或python的任何文件)路径来计算执行时间。请分享你的建议 我知道在python代码中使用时间模块可以获得执行时间。如何在python中执行Javascript和java代码,并在公共函数中获得执行时间 我试过下面的方法 import time def get_exectime(file_path): # pass
import time
def get_exectime(file_path): # pass path of any file python,java,javascript, html, shell
start_time=time.time()
# execute the file given here. How to execute all file types here?
end_time=time.time()
exec_time=end_time-start_time
print(exec_time)
有没有其他方法可以实现这一点?您可以使用
时间
模块:
import time
start_time = time.time()
#code here
print("--- %s seconds ---" % (time.time() - start_time))
import time
start_time = time.time()
# your code
end_time = time.time()
print("Total execution time: {} seconds".format(end_time - start_time))
我想您可能需要
时间模块。这是python中测量执行时间的最简单方法。看看我的例子
import time
start_time = time.time()
a=1
for i in range(10000):
a=a+1
end_time = time.time()
total_time = end_time-start_time
print("Execution time in seconds: %s ",total_time)
输出:
Execution time in seconds: %s 0.0038547515869140625
>>>
与其他答案相反,我建议使用timeit
,它的设计初衷是测量执行时间,也可以用作独立工具:
它不仅提供执行的实时性,还提供使用的CPU时间,这不一定是同一回事。首先以管理员身份打开命令提示符(CMD)并键入-
pip安装人性化
代码:
输出:
Execution time in seconds: %s 0.0038547515869140625
>>>