Search code examples
pythonvideoframe-ratetiming

How can I time prints consistently


I'm training my python abilities by making a bunch of generally useless code and today I was attempting to print Bad apple in the console using ASCII art as one does, I did everything just fine until I had to time the prints so they end in 3 minutes and 52 seconds maintaining a consistent framerate. I tried just adding a time.sleep()in between prints hoping it would all just magically work but obviously it didn't.

I customized a version of this git https://github.com/aypro-droid/image-to-ascii to transform frames to ASCII art and used https://pypi.org/project/opencv-python/ for transforming the video to frames

here is my code:

import time
frames = {}
#saving each .txt frame on a dict
for i in range(6955):
    f = open("Frames-to-Ascii/output/output{0}.txt".format(i), "rt")
    frames['t{0}'.format(i)] = f.read()
    f.close()
#start "trigger"
ini = input('start(type anything): ')
start = time.time()
#printing the 6954 frames from the dict
for x in range(6955):
    eval("print(frames['t{0}'])".format(x))
    #my attempt at timing
    time.sleep(0.015)
end = time.time()
#calculating how much time the prints took overall, should be about 211.2 seconds evenly distributed to all the "frames"
print(end-start)

frame example: here

I'm attempting to time the prints perfectly to the video so I can later use it somewhere else, any tips?


Solution

  • What I understand is that you need to print the frames at a given constant rate? If yes, then you need to evaluate the time used to print and then sleep for the delay minus the time to print. Something like:

    for x in range(6955):
        start = time.time()
        print("hips")
        end = time.time()
        time.sleep(0.5-(end-start))
    

    Thus the loop will take (approximatively) 0.5s to run. (Change the value accordingly to your needs).

    Of course if a single print takes more time than the delay, you need to find another strategy: for example stepping over the next frame, etc.