user3250719
user3250719

Reputation: 105

Counting Time of code running Python

How could I knwow the execution time of a code in Python in microseconds? I have tried time.time and timeit.timeit but I can't have a good output

Upvotes: 8

Views: 22095

Answers (6)

Nishant Nawarkhede
Nishant Nawarkhede

Reputation: 8400

Try this,

import time
def main():
    print [i for i in range(0,100)]
    
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0.00255163020819 seconds

Update

Don't forget to import time

Place this line start_time = time.clock() before your code and place this

print time.clock() - start_time, "seconds" at the end of code.

Update

# Top Of script file.
def main():
        print [i for i in range(0,100)]

start_time = time.clock()
#YOUR CODE HERE - 1

main()

#YOUR CODE HERE - N
print time.clock() - start_time, "seconds"

You can also write decorator for measuring time,

import time


def dec(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        func(*args, **kwargs)
        end = time.time()
        print(end - start)
    return wrapper


@dec
def test():
    for i in range(10):
        pass


test()
# output shows here 

Upvotes: 8

jackfizee
jackfizee

Reputation: 318

Personally, I use a dedicated object defined by the following class:

import time
class Chronometer():
    def __init__(self):
        self.__task_begin_timestamp = {}

    def start(self,task_name):
        """
        Start a new task chronometer

        Parameters
        ----------
        task_name : str
            task id

        Raises
        ------
        ValueError
            if a running task already exists with that name
        """
        if task_name in self.__task_begin_timestamp:
            raise ValueError("A running task exists with the name {0}!".format(task_name))
        self.__task_begin_timestamp[task_name] = time.time()

    def stop(self,task_name):
        """
        Stop and return the duration of the task

        Parameters
        ----------
        task_name : str
            task id

        Returns
        -------
        float
            duration of the task in seconds

        Raises
        ------
        ValueError
            if no task exist with the id `task_name`
        """
        if not task_name in self.__task_begin_timestamp:
             raise ValueError("The {0} task does not exist!".format(task_name))
        duration = time.time() - self.__task_begin_timestamp[task_name]
        del self.__task_begin_timestamp[task_name]
        return duration

chrono = Chronometer()
chrono.start("test")
chrono.start("test2")
time.sleep(3)
print(chrono.stop("test"))
# 3.005409002304077
time.sleep(3)
# 6.00879693031311
print(chrono.stop("test2"))

Upvotes: 0

William Rusnack
William Rusnack

Reputation: 948

update
I highly recommend just using the library cProfile and then visualize it with snakeviz

You can then get an interactive display that gives you a much better idea of what is happening in your code.

You can then select specific parts of your code to view and there is a sortable table that lists all the functions and their times.

Forget my original answer and everyone else's answers. Just use snakeviz (I'm not a part of the snakeviz project).

snakevis time display

original answer below

There is a really good library called jackedCodeTimerPy

It gives really good reports like

label            min          max         mean        total    run count
-------  -----------  -----------  -----------  -----------  -----------
imports  0.00283813   0.00283813   0.00283813   0.00283813             1
loop     5.96046e-06  1.50204e-05  6.71864e-06  0.000335932           50

I like how it gives you statistics on it and the number of times the timer is run.

It's simple to use. If i want to measure the time code takes in a for loop i just do the following:

from jackedCodeTimerPY import JackedTiming
JTimer = JackedTiming()

for i in range(50):
  JTimer.start('loop')  # 'loop' is the name of the timer
  doSomethingHere = 'This is really useful!'
  JTimer.stop('loop')
print(JTimer.report())  # prints the timing report

You can can also have multiple timers running at the same time.

JTimer.start('first timer')
JTimer.start('second timer')
do_something = 'amazing'
JTimer.stop('first timer')

do_something = 'else'
JTimer.stop('second timer')

print(JTimer.report())  # prints the timing report

There are more use example in the repo. Hope this helps.

https://github.com/BebeSparkelSparkel/jackedCodeTimerPY

Upvotes: 2

cft
cft

Reputation: 16

from time import time
chrono = []
chrono.append(time())
# your code 1 here
chrono.append(time())
print "duration 1 is : ", str((chrono[1] - chrono.pop(0))*1e6), " µs"
# your code 2 here
chrono.append(time())
print "duration 2 is : ", str((chrono[1] - chrono.pop(0))*1e6), " µs"

Edit : In fact I use this in a function: variable chrono is declared (chrono = []) and initilized (chrono.append(time())) just before the first code I want to measure. Then I call print_time("a useful message") which is defined :

def print_time(message):
    chrono.append(time())
    timestamp = chrono[1] - chrono.pop(0)
    print message + ":\n {0}s".format(timestamp)

Output is :

a useful message:
0.123456789s

with chrono.pop(0), the last value inserted becomes the first in list and at next call of print_time there's no need to manage items in list : its lenght is always 2 and in the right order.

Upvotes: 0

Samfaitmal
Samfaitmal

Reputation: 80

A good way to profile is to use cProfile library :

python -m cProfile [your_script].py

It will output the execution time, number of cycles, etc... of each procedure of your code.

Upvotes: 1

Andy
Andy

Reputation: 50540

The easiest way is something like this, however, this requires that the script runs for at least a tenth of a second:

import time
start_time = time.time()
# Your code here
print time.time() - start_time, "seconds"

There are profilers available that can also help.

If I have a small script that looks like this

print "Hello, World!"

And want to profile it

>python -m cProfile test.py
Hello, world!
         2 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 test.py:1(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}

This shows that it took 0.001 seconds to run and also provides other information about calls that occurred while executing the code.

Upvotes: 6

Related Questions