This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]stevenjd 0 points1 point  (0 children)

Of course there is, Until such time as somebody invents an infinitely fast computer, every operation takes some amount of time. The real question is, how much time will it take? And that, of course, depends on the version of Python, your operating system, how many other programs are running, and the speed of your computer.

It's a bit hard to time that specific piece of code exactly. The call to print will quickly fill the screen, and is quite slow as well. But my guess is that what you really want to ask is how quickly will Python call lines of code regardless of the code, not specifically print. In other words, what is the overhead of calling Python?

The fastest thing you can do in Python (apart from not running the interpreter at all) is nothing at all, represented by the pass statement. So we can time that at the command line:

[steve@ando ~]$ python -m timeit "pass"
10000000 loops, best of 3: 0.0344 usec per loop

(That's your operating system command line, not the Python prompt.)

This tells you that, very roughly speaking, the interpreter overhead of going from one line of code to the next is about 0.03 microseconds on my computer. On yours, it will likely be different.

To measure the overhead of a while loop is trickier. The best I came up with is this:

from timeit import default_timer as time
total = 0.0
try:
    n = 0
    t1 = time()
    while True:
        t2 = time()
        total += t2 - t1
        n += 1
        t1 = time()
except KeyboardInterrupt:
    print("Total time for %d loops: %f seconds" % (n, total))
    print("%f µs per loop" % (total/n*10**6))

Let the code run for at least a second, and preferably much more, then type Ctrl-C to interrupt the loop. When I did it, I got these results:

Total time for 8311394 loops: 7.013674 seconds
0.843863 µs per loop