Reputation: 8580
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.
Upvotes: 0
Views: 2275
Reputation: 1001
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)
Upvotes: 0
Reputation: 420
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
.
pytictoc contains a class TicToc which replicates the functionality of MATLAB’s tic and toc for easily timing sections of code. Under the hood, pytictoc uses the default_timer function from Python’s timeit module.
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.
Upvotes: 1
Reputation: 547
Would PyFlame from Uber, suit your purposes?
Pyflame is a high performance profiling tool that generates flame graphs for Python. Pyflame is implemented in C++, and uses the Linux ptrace(2) system call to collect profiling information. It can take snapshots of the Python call stack without explicit instrumentation, meaning you can profile a program without modifying its source code. Pyflame is capable of profiling embedded Python interpreters like uWSGI. It fully supports profiling multi-threaded Python programs.
Upvotes: 0
Reputation: 16772
You can use timeit
, that;
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
i.e.
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:
Upvotes: 1