I'm making a script with ruby that must render frames at 24 frames per second, but I need to wait 1/24th of a second between sending the commands. What is the best way to sleep for less than a second?
Asked
Active
Viewed 1.7e+01k times
2 Answers
211
sleep(1.0/24.0)
As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.
You could try one of these solutions:
- Use a timer which fires 24 times a second with the drawing code.
- Create as many frames as possible, create the motion based on the time passed, not per frame.

Georg Schölly
- 124,188
- 49
- 220
- 267
-
14@Funkodebat I'm pretty sure every basic ruby runtime does this for you. – Georg Schölly Sep 29 '12 at 09:13
-
2@JosephSilvashy: I don't have any insight into the ruby interpreter, but ruby mri does not do memoization by default. But I hope it does this kind of optimization while converting the source code to byte code. – Georg Schölly May 16 '13 at 09:01
-
8It's a good idea to extract the 1.0/24.0 value to a variable for the DRY principle. Other pieces of code will need that value too, so you should keep it in a central location to avoid duplication. If performance is a side-effect, then great! – James Watkins Feb 13 '14 at 17:01
-
1You should definitely extract the constant, and definitely not do it with the reason "all the performance you can get" – Blake Jul 29 '14 at 10:58
-
1On a performance note, I was curious about this and wrote 2 quick functions. One that adds 1.0/24.0 to a variable 10 million times and another using a CONST equaling 1.0/24.0 10 million times. Then I ran those functions 100 times each and took the averages. Ran THAT script 4 or 5 times. Results: Using the constant vs recalculating provided about a 20% speed increase consistently in each trial. – mharris7190 Apr 22 '15 at 06:38
-
4But it's a quick division, ran once per frame. Hopefully the rendering of the frame itself is many magnitudes greater in computational complexity. This is a brilliant example of premature optimization. – Alan H. Aug 10 '15 at 23:08