如何获取代码的执行时间? [英] How to get the execution time of the code?

查看:65
本文介绍了如何获取代码的执行时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to calculate the execution time of code of various languages such as java, python, javascript. How to get the execution time of these codes. Is there any tool available in python packages or any other to calculate the execution time by passing the file(any file java or python) path. Please share your suggestion.

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

I am aware of getting execution time by using time module in python code. How to execute Javascript and java codes in python and get the execution time in common function.

我尝试了以下方法.

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)

有没有其他方法可以实现这一点?

Is there any other method available to achieve this?

推荐答案

与其他答案相反,我建议使用 timeit,它的设计初衷是为了测量执行时间,并且可以也可用作独立工具:https://docs.python.org/3/图书馆/timeit.html

Contrary to other answers, I suggest using timeit, which was designed with the very purpose of measuring execution times in mind, and can also be used as a standalone tool: https://docs.python.org/3/library/timeit.html

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

It will give you not only the real time of execution, but also CPU time used, which is not necessarily the same thing.

这篇关于如何获取代码的执行时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆