Trying to make a file that tests how many seconds it takes for python to use a while loop to count how many seconds 1000 loops takes. Not working, I don't know why. Every time I run this it outputs "('It took 0,0')"...The while loop didn't start.

import time
import math

count = 0
PrevTime = time.time()

while count < 1000:
    count +=1
    if count == 1000:
        print ("It took ", time.time() - PrevTime)
        raw_input()

Dani AI

Generated

The program almost certainly ran; what you saw was the combination of a very small elapsed time and Python 2 printing semantics rather than a stalled loop. and were on the right track: tiny iteration counts can produce times near zero on modern hardware, and ’s note about not doing I/O inside the measured loop is important. Additional points below will make timing repeatable and easier to read.

A simple, modern pattern is to use a high-resolution timer and do the work outside any print/I/O. The example below uses time.perf_counter() (Python 3.3+) and does a tiny amount of work inside the loop so the result is measurable on fast machines.

import time

def measure(n):
    start = time.perf_counter()
    acc = 0
    for i in range(n):
        acc += (i & 1)  # small operation so loop cost is measurable
    elapsed = time.perf_counter() - start
    print("Elapsed: {:.6f} s for {} iterations".format(elapsed, n))
    return elapsed

For microbenchmarks use the built-in timeit module because it handles repeats, warmups, and avoids common pitfalls. See the time.perf_counter() docs for why it is preferred over time.time() on many platforms.

Quick troubleshooting checklist:

  • If using Python 2, print("It took ", val) prints a tuple — use print "It took", val or format strings instead.
  • Move all printing/raw_input out of the timed region (I/O dominates timing).
  • Increase iterations (and repeat runs) to get stable numbers; compute the average or median.
  • Prefer timeit for small workloads; use a slightly heavier inner operation if timing still reports zero.
  • Be aware CPU frequency scaling or other load on the machine can affect short timings.

Recommended Answers

All 3 Replies

Lol, try making 1000 into 100000. It's doing it too quick and rounding down the time.

Try to run the loop 1 000 000 times instead of 1000. On my machine, it takes 0.0818829536438 seconds for 1 million times. See also the module timeit.

Generally, the structure is more like this.

import time
 
count = 0
PrevTime = time.time()
 
while count < 1000:
    count +=1

print ("It took ", time.time() - PrevTime)
raw_input()

Using "==" in a loop is dicey in more complicated loops, as the counter could be incremented more than once. If you want to do this, use
if count > 999: instead

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.