How to precisely measure function execution time

I have a piece of code which is quite slow (the code interacts with the database) and need to measure its execution time to know if i make it quicker or slower. Could you please share what tools would you use to measure it?
Best Regards and thanks for your great help so far!

The easiest would be to add some functions at the beginning and end of the function.

def myFunc():
    start =
    end =
    execTime =,end)

millisBetween() should work in most cases, but if you need something for faster scripts you could use

1 Like

Likely that the database is the source of your slowness, depending on what you define as “slow”.

I would make sure you/or someone, look at the indexing of involved tables, and query execution plan. DB queries are notorious for unexpected performance issues.

For code execution time, I always use java.lang.System.nanoTime()

from java.lang import System

start = System.nanotime()
# your code
end = System.nanotime()
print 'Took {} nanosecodes'.format(end-start)

that will do the trick thank you

Always use System.nanoTime() for benchmarking. It uses a monotonic clock that is synchronized across processors, and is immune to system clock adjustments. If your thread gets interrupted and migrated, .nanoTime() will be most consistent.

1 Like

thanks a lot for your feedback