Issue
I made a basic test program to calculate the time taken by python to count till 100000. But there is a lot of time difference when i put print function inside the loop vs outside the loop.
n = 0
while(n<1000000):
n+=1
print(n)
n = 0
while(n<1000000):
n+=1
print(n)
Why is there a time difference and how can i fix it?
Solution
The print() function is actually a very expensive process, relatively speaking. It's well known for slowing down programs if you print too often. As such, there are often a lot of other libraries that are used for faster debugging or logging in code for production. In your situation however, just consider that, in your loop, there are two things you're trying to do:
- Increase the value of
n
by 1 : This is a very small instruction that will take only a single processor cycle or two at maximum. - Print the value of
n
to the screen : This requires the system to first create a string buffer (which requires allocating memory for a new string), convert the integern
into a string by extracting each digit one by one and adding it to the string buffer (which can take around 4 or 5 processor cycles per digit inn
), convert the string buffer into a string, use the system API to fetch a reference to the console, copy the string into the console's buffer, then flush the console's buffer so that the text appears on the screen. On average, that can easily take a few tens to hundreds of processor cycles.
As such, you can see that, when you place the print statement outside the loop, the loop only takes around a few million processor cycles to complete, which can be less than a second depending on your system. But when you place the print statement inside the loop, it can take a few tens to hundreds of millions of cycles to complete the loop, turning into a sizeable delay.
As such, it's important to log information in your code, but it's also important to know when to not log the information in your code, simply to save memory (the size of the log file or output) and processing power.
Answered By - Anoop Vargheese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.