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?
2 Answers
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.
-
14@Funkodebat I'm pretty sure every basic ruby runtime does this for you. Sep 29, 2012 at 9: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. May 16, 2013 at 9: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! Feb 13, 2014 at 17:01
-
1You should definitely extract the constant, and definitely not do it with the reason "all the performance you can get"– BlakeJul 29, 2014 at 10:58
-
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, 2015 at 23:08