Master-chip Master-chip - 1 year ago 75
Python Question

Python 3 - Don't check variable every iteration

I currently have a

, which is going through an incredible number of iterations to check something, and when it goes to a new iteration, I need it to check whether or not a variable I have is the same size of the current iteration.

Here is an example code of what I'm doing:

import datetime
now =
printcounter = 0
for i in range(3,100000000000+1,2):
if (printcounter == 1000000000):
print(i,"at %d" %now.hour, "hours and %d" % now.minute, "minutes.")
printcounter = 0
#Do operation
printcounter += 1

However, since it's going through possibly millions of math heavy operations before I get my answer, I noticed that by striping this code of the 'printcounter' variable and not giving me a progress report gave me a significant speedup, by whole minutes sometimes.

Is there any way of only checking whether or not the 'printercounter' variable is equal to 10000, however without making it check every single iteration?

I personally can't think of anyway without resorting to nesting for loops, which can get very dirty, and I'd rather not have.

By the way, I'm using Windows 8.1, Python 3.5.1, if that makes any difference.


I understand that it takes a significant portion of time to print, however, if I instead print to a file; my harddisk being very fast, then I still get the same, albeit reduced, difference in time. Also, I have been wanting to get the solution to this implemented in a lot of other scripts, so even if it's not a major problem here, I'd still like to know how to do it.

Edit 2:

Perhaps it's my fault for not being clear. I was looking to see if it was possible to check a value every once in a while, not every single time. For example, I don't want my code to check if 'printcounter' is equal to 1000000000 when it's 1, that's ridiculous. I know machines operate ridiculously fast, and so it doesn't matter, but I was curious to see if it was possible to reduce the number of times it checks that way, rather than having a dumb code which allows itself to be sloppy or lazy just because it's quick enough to correct for it.

Answer Source

If you don't want to check the variable every iteration, make it unnecessary...
by doing something like this instead:

import datetime

iterations = 100000000000
iterations = 100000
subiterations = 10000
chunks, remaining = divmod(iterations, subiterations)

now =
printcounter = 0
for i in range(chunks):
    for j in range(subiterations):
        #Do operation

    printcounter += subiterations
    print('{:,d} at {} hours {} minutes'.format(printcounter, now.hour, now.minute))

if remaining:
    for j in range(remaining):
        #Do operation

    printcounter += remaining
    print('{:,d} at {} hours {} minutes'.format(printcounter, now.hour, now.minute))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download