[英]measure times spent per line in runtime python
Is there any tool that measures how much time spent on each line of code while executed in runtime and shows some visualization of the result to help developer get an idea of which lines are the most time consuming in execution?是否有任何工具可以测量在运行时执行时每行代码花费的时间并显示结果的一些可视化以帮助开发人员了解哪些行在执行中最耗时?
Im intrested for such tool for python, and im working on pycharm.我对这样的 Python 工具很感兴趣,我正在研究 pycharm。
You can use timeit
, that;您可以使用timeit
,即;
Measure execution time of small code snippets测量小代码片段的执行时间
import timeit
start_time = timeit.default_timer()
# the line of code you want to measure the time for
elapsed = timeit.default_timer() - start_time
ie IE
import timeit
start_time = timeit.default_timer()
a = 5 + 2 / 1
b = a + 2
elapsed = timeit.default_timer() - start_time
print"Time taken: ", elapsed
OUTPUT:输出:
I think what you asked for is a way to print the elapsed time for each line, which is extremely inefficient and difficult (and unnecessary).我认为您要求的是一种打印每行经过时间的方法,这是非常低效和困难的(并且是不必要的)。 You do not have to calculate the time elapsed for lines like您不必计算像这样的行经过的时间
foo = 1
That being said, you can put a timer at where you doubt your code is being slow.话虽如此,您可以在怀疑代码运行缓慢的地方放置一个计时器。 A useful module available on pip
is pytictoc
. pip
上一个有用的模块是pytictoc
。
pytictoc contains a class TicToc which replicates the functionality of MATLAB's tic and toc for easily timing sections of code. pytictoc 包含一个类 TicToc,它复制了 MATLAB 的 tic 和 toc 的功能,以便轻松对代码段进行计时。 Under the hood, pytictoc uses the default_timer function from Python's timeit module.在幕后,pytictoc 使用 Python 的 timeit 模块中的 default_timer 函数。
from pytictoc import TicToc
t.tic() #Start timer
# some of your codes here, e.g.
for ii in range(1000):
pass
t.toc() #Time elapsed since t.tic()
Elapsed time is 1.35742 seconds.经过的时间是 1.35742 秒。
Would PyFlame from Uber, suit your purposes? Uber 的PyFlame 是否适合您的目的?
Pyflame is a high performance profiling tool that generates flame graphs for Python. Pyflame 是一种高性能分析工具,可为 Python 生成火焰图。 Pyflame is implemented in C++, and uses the Linux ptrace(2) system call to collect profiling information. Pyflame 是用 C++ 实现的,并使用 Linux ptrace(2) 系统调用来收集分析信息。 It can take snapshots of the Python call stack without explicit instrumentation, meaning you can profile a program without modifying its source code.它可以在没有显式检测的情况下获取 Python 调用堆栈的快照,这意味着您可以在不修改其源代码的情况下分析程序。 Pyflame is capable of profiling embedded Python interpreters like uWSGI. Pyflame 能够分析嵌入式 Python 解释器,如 uWSGI。 It fully supports profiling multi-threaded Python programs.它完全支持分析多线程 Python 程序。
import time
def elapsed_time(start, end):
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("Elapsed Time: {:0>2}:{:0>2}:{:05.2f}"
.format(int(hours),int(minutes),seconds))
#Test
start = time.time()
# your routine
end = time.time()
elapsed_time(start, end)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.