1

I want to get the execution time of several portions of my code. Currently I am using time.time() but I feel a bit dumb when writing again and over again code like this:

start = time()
function1(args1)
print("Execution of function1: {}".format(time()-start))

start = time()
function2(args2)
print("Execution of function2: {}".format(time()-start))

start = time()
function3(args3)
print("Execution of function3: {}".format(time()-start))

Please do you know any smarter way to do this? I couldn't find any module that would enable to do things like this (for instance):

chrono("Execution of function1")
function1(args1)

chrono("Execution of function2")
function2(args2)

chrono("Execution of function3")
function3(args3)

2 Answers 2

3
import time

def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        print '%r (%r, %r) %2.2f sec' % \
            (method.__name__, args, kw, te-ts)
        return result
    return timed


@timeit
def function1():
    time.sleep(1)
    print 'function1'

>>> function1()
function1
'function1' ((), {}) 1.00 sec

Use this decorator for function definition.

Reference:

https://www.zopyx.com/andreas-jung/contents/a-python-decorator-for-measuring-the-execution-time-of-methods

Sign up to request clarification or add additional context in comments.

Comments

0

Take a look at the timeit module.

https://docs.python.org/3/library/timeit.html

From that page,

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.