Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I time script execution time in PyCharm without adding code every time?

Tags:

python

pycharm

Currently I just add the following lines around my code:

import time
start_time = time.time()

# my code here

print "time elapsed: {:.2f}s".format(time.time() - start_time)

Is it possible to achieve the same without adding code to every script I want to time? Either adding something in run configuration or using a plugin?

like image 759
KarolisR Avatar asked Feb 26 '16 15:02

KarolisR


People also ask

How do I show runtime in PyCharm?

The command Show Running List of the menu Run is only enabled if there are active applications. If no applications are active, the command is greyed out. From the main menu, select Run | Show Running List. In the top-right corner of the editor, PyCharm shows a list with all active applications .

How do I get time of a python program's execution?

Run the %timeit command on a command-line or jupyter notebook to get the execution time of a single line of code.

Can you run scripts on PyCharm?

With PyCharm, you can run entire applications as well as particular scripts.


3 Answers

You can profile your script by hitting the 'profile' button (it is to the right of the 'run', 'debug', and 'run with coverage' buttons):

Profile button

Among the output, you will find the name of the script itself, and the time needed to run it.

Note: the function is available in PyCharm PROFESSIONAL 2017.1 for the Linux platform; other installations might not provide the profiler button.

like image 184
lev Avatar answered Oct 23 '22 10:10

lev


Since not everyone has PyCharm Pro which can measure script's running time, here is a simple solution that uses decorator. We only need to add a single line of code to measure the running time of any function as follows:

import time

def timeit(func):
    """
    Decorator for measuring function's running time.
    """
    def measure_time(*args, **kw):
        start_time = time.time()
        result = func(*args, **kw)
        print("Processing time of %s(): %.2f seconds."
              % (func.__qualname__, time.time() - start_time))
        return result

    return measure_time

@timeit
def func():
    for _ in range(3):
        time.sleep(1)

if __name__ == "__main__":
    func()

Output:

Processing time of func(): 3.00 seconds.
like image 14
Vinh Khuc Avatar answered Oct 23 '22 09:10

Vinh Khuc


I know it is late but I wanted the same thing and here is what I did:

Create another python file in the directory of your codes:

import time
st=time.time()
import test
print("----%.2f----"%(time.time()-st))

where test is your program name. So if you want to run any program just run it from here by just changing test.

Keep in mind that import runs the code normally if you haven't used:

if __name__=="__main__":
like image 5
Vedant Kandoi Avatar answered Oct 23 '22 11:10

Vedant Kandoi