如何获取代码的执行时间?

How to get the execution time of the code?

我想计算java、python、javascript等各种语言代码的执行时间。如何获取这些代码的执行时间。 python 包或任何其他工具中是否有任何工具可以通过传递文件(任何文件 java 或 python)路径来计算执行时间。请分享您的建议。

我知道通过在 python 代码中使用时间模块来获取执行时间。如何在python中执行Javascript和java代码,并获取common函数中的执行时间。

我试过下面的方法。

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))

您可以使用 time 模块来做到这一点:

import time
start_time = time.time()
# your code
end_time = time.time()
print("Total execution time: {} seconds".format(end_time - start_time))

我认为您可能需要 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,它的设计目的就是测量执行时间,也可以用作独立工具:https://docs.python.org/3/library/timeit.html

它不仅会给你实时执行时间,还会给你CPU使用时间,这不一定是一回事。

首先以管理员身份打开命令提示符 (CMD) 并键入 - 在 python 中安装 "humanfriendly" 包 pip install humanfriendly

代码:

from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))

输出: