'How do I ensure that a timed loop performs the same number of iterations from trial to trial when the same duration is specified?

from datetime import datetime, timedelta

ntrials = 3                                                    # specify number of trials
duration = 1                                                   # specify duration (in seconds)

for i in range(1,ntrials+1):
    count = 0                                                  # (re)initialize count to zero
    end_time = datetime.now() + timedelta(seconds=duration)    # set trial duration
    while datetime.now() < end_time:                           # check if duration has elapsed
         count += 1                                            # count number of iterations
    print("trial: ",i,"\tcount: ",count)                       # display results


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source