Pijus Kumar
Pijus Kumar

Reputation: 25

Why does the execution time of the same block of python differ?

I have written a python script and am trying to measure the execution time using datetime time like so:

from datetime import datetime
startTime = datetime.now()
// here several methods are called
runtime = datetime.now()-startTime

Execution time of the same code block is different when I run the script different times. For instance, I ran the script and it took .002 sec but when I ran the same script 2 hours later it shows a different execution time.

Is there anything relating to the CPU processing that can affect the execution time of a python code.

Upvotes: 2

Views: 1493

Answers (1)

BudgieInWA
BudgieInWA

Reputation: 2255

Modern desktop operating systems, like the one you and I are using now, are always performing many task at once. This is called multitasking. For example handling mouse and keyboard input, managing network traffic, rendering animations, blinking the text cursor and a million other things.

A CPU can actually only do one thing at a time, but it can achieve multitasking by very quickly switching between all of the tasks that need doing. It switches between different processes thousands of times per second so that it seems like it is doing them all at the same time.

When your computer runs your python program, a little of your program will be executed by the CPU then a little of something else, then eventually a little more of your program. Depending on what else there is that needs doing, even a program that executes exactly the same number of instructions will take a different amount of "wall-clock time" to complete each time it is run.

On top of all that, the python interpreter, the program that is readying your python script and deciding what to do, is extremely complex and is doing many things behind the scenes to try to run your python quickly. Because of this it might do slightly more or less work each time it interprets your script.

I encourage you to read the Wikipedia article on Computer Multitasking; it is a good introduction to the concept.

Upvotes: 4

Related Questions