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

4
我想计算各种语言(如Java,Python,Javascript)的代码执行时间。如何获取这些代码的执行时间?是否有可用于Python包或其他任何工具来通过传递文件(任何Java或Python文件)路径来计算执行时间?请分享您的建议。
我知道可以使用Python代码中的time模块来获取执行时间。如何在Python中执行Javascript和Java代码并在通用函数中获取执行时间?
我尝试了以下方法。
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)

有没有其他方法可以实现这个目标?

5个回答

6
你可以使用time模块来实现这个功能:
import time
start_time = time.time()
# your code
end_time = time.time()
print("Total execution time: {} seconds".format(end_time - start_time))

5
与其他答案不同,我建议使用timeit,它是专门设计用于测量执行时间的工具,并且也可以作为独立工具使用:https://docs.python.org/3/library/timeit.html。它不仅会给出实际执行时间,还会给出CPU使用时间,这两个时间并不完全相同。

2
import time
start_time = time.time()

#code here

print("--- %s seconds ---" % (time.time() - start_time))

0
我觉得你可能需要使用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
>>> 

-1

首先在管理员模式下打开命令提示符(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))

输出:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接