Zen_Master
Zen_Master

Reputation: 21

Make a loop last once second using datetime?

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)

Upvotes: 0

Views: 357

Answers (2)

GSazheniuk
GSazheniuk

Reputation: 1384

  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

Upvotes: 1

Taohidul Islam
Taohidul Islam

Reputation: 5414

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()

Upvotes: 1

Related Questions