0

Bright minds of Stackoverflow, I have a quest for you. Currently I am running a loop in which calculations and data aquisition happen. These get more and more complicated over time. I want each run of the loop to last exactly one second. Due to the growing time of the calculations a simple "sleep(1)" at the end does not really help.

while True:

    #here calculations happen that take more and more time

    print 'some of the data'

    sleep(1)

I was hoping to use datetime to calculate the seconds/milliseconds before these calculations and after to enter the difference into the sleep command. But i can't quite get my head around it. Can anyone help me out?

    a=datetime.now()
    #calculations
    b=datetime.now()
    calctime=(b-a).total_seconds()
    sleep(1-calctime)
Zen_Master
  • 21
  • 7
  • You might find some useful information [here](https://stackoverflow.com/questions/50471895/inaccurate-while-loop-timing-in-python/50472499#50472499) – MoxieBall Jun 21 '18 at 17:58
  • Since `total_seconds()` is equivalent to `time / timedelta(seconds=1)`, should you not do `sleep(1 * calctime)`? – Tomas Farias Jun 21 '18 at 18:04
  • No, I want to reduce the sleep, which is one second, by the time the calculation in the loop takes. Because the growing time of the calculation makes the loop last one second + calctime. – Zen_Master Jun 22 '18 at 07:34

2 Answers2

1

Try this:

from datetime import datetime
import time
def test():
    a = datetime.now()
    # calculations
    b = datetime.now()
    calctime = (b - a).total_seconds()
    print("one")
    time.sleep((1 - calctime) if (1-calctime)>0.0 else 0) #if your calculation already took 1 or more than 1 second then then make the waiting time 0
    print("two")

test()
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
1
  a=datetime.now()
  #calculations
  b=datetime.now()
  calctime=b-a
  ms = calctime.microseconds
  if calctime.seconds == 0:
      sleep(1-ms/1000000)

Additional info here: Python speed testing - Time Difference - milliseconds

GSazheniuk
  • 1,340
  • 10
  • 16