-1

I have a python program defined by a function myFunc(m,n)

Basically, the function contains two for loops.

def myFunc(m, n) : 
    for i in range(m) : 
        for j in range(n) : 
            # do it ...
    return 

I would like to calculate the time elapsed for m,n=20,20

I do it like this:

start_time = time.time()
b = myFunc(m,n)
elapsed_time = time.time() - start_time
print elapsed_time

The result is 0.0 almost always. Why?

Kira
  • 333
  • 4
  • 11

2 Answers2

4

Because time.time() - time.time() will be 0.0 when myFunc doesn't take very long.

cdonts
  • 9,304
  • 4
  • 46
  • 72
Chad S.
  • 6,252
  • 15
  • 25
3

Per the time.time docs,

even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.

So if myFunc takes less than a second and you are using such an OS, then the difference between two calls of time.time could be 0.0.

You could use timeit.default_timer instead of time.time. timeit.default_timer will choose the best timer (time.time, time.clock or time.perf_counter) for your system.

Also note that the timeit module offers more accurate ways to test the performance of code snippets.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677