Ruby sleep or delay less than a second? - ruby

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?

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.

Pass a float to sleep, like:
sleep 0.1

Related

ticks and hours in NetLogo

Is there some type of conversion for ticks to a unit of real time? I would like my program to simulate a 48 hour experiment. Does anyone have any suggestions on how to do this? Thanks!
How quickly do things change in your experiment? From system dynamics, a good rule of thumb is to have a discrete clock tick 4 times during the smallest interval of real time in which something meaningful happens in the modelled system. For example, if you would expect to see changes every minute, then you would have 4 ticks each minute (and your ABM rules about updating the system would be calculated on the basis of 15 seconds) and then run the simulation for 11,520 (=48x60x4) ticks.

Delphi timer more precise than milliseconds

I've got a program in Delphi which takes in frames from an external application in 25 hertz (25 times per seconds) and then converts it to 60 hertz (60 frames per second) by creating 1-2 extra frames. I need to output these extra frames by continuously building a frame buffer and outputting the frames from here from a separate thread. The problem is that 1000/60 is 16.66667 which means I can't just send the frames in a "interval" on 16 or 17 milliseconds, I need it to be more precise. How do I do this in Delphi/Windows?
Use a multimedia timer via the Win32 API timeSetEvent() or CreateTimerQueueTimer() function.
You probably need to make use of both of the following:
The high resolution timer. This is available through the QueryPerformanceCounter Win32 function, and also wrapped by the Delphi TStopwatch type.
A waitable timer. This allows you to set a due date in the future and have your thread block, and be woken at the due date.
Both of these have higher resolution than the GUI timer, and should suffice for your needs. Read an overview here: http://msdn.microsoft.com/en-gb/library/windows/desktop/ms644900.aspx

Understanding Delta time in LWJGL

I've started looking into lwjgl and I'm particularly having trouble understanding how Delta works. I have browsed other questions and websites related to this but it is still a confusing topic to wrap my head around. It would be great if someone here can help me out so please bear with me.
I understand that the Delta time for 60fps would be 16, around double that if the frame-rate is 30. I don't understand how this is calculated. Is it the time it takes between frames? Sorry for the noobish question.
private long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
private int getDelta() {
long currentTime = getTime();
int delta = (int)(currentTime - lastTime);
lastTime = getTime();
return delta;
}
As opiop65 already said, the delta time is simply the time spent between your last frame's beggining and your current frame's beggining.
How does it work?
Delta time can be any kind of unit: nanoseconds, milliseconds (<- usually this is the standard) or seconds. As you said delta time is 16 when the game is running on 60FPS and 32 when the game runs on 30FPS. As for the why, it's simple: In order for a game to run at 60 frames per second it has to produce a frame every 1000/60 (= 16.666667) milliseconds, but if it running at 30 frames then it has to produce a frame every 1000/30 (= 33.333333) milliseconds.
But why do we use delta time?
We use delta time because we want to do movement and all sorts of stuff time dependant and not frame depentdant. Lets say that you want one of your game's character to move 1 unit horizontally per second. How do you do that? Obviously, you can't just add 1 to the character's location's X value, because it would get moved 1*x times per second where x is equal to your FPS (assuming that you would update the character every frame). That would mean that if somebody runs the game on 1 FPS his character would move 1 units per second, where if somebody runs the game on 5000 FPS his character would move 5000 units per second. Of course that is unacceptable.
One could say that he would move the character 1/16.6667 units on every update but then again if somebody has 1 FPS he moves 1/16.6667 units per second, opposed to that guy who runs on 5000 FPS, thus moving 5000*(1/16.6667) units per second.
Yes, you can enable V-Sync but what if somebody has a 120Hz monitor (or even higher) and not 60Hz?
Yes, you can lock the framerate but your players wouldn't be too happy about that. Also that wouldn't stop the character from slowing down when the game drops below 60FPS. So what now?
Delta time to the rescue!
All you have to do is just to move your character 1*delta on every update.
Delta time is low if the game runs on a high FPS and high if the game runs on a low FPS thus making those character go slower who runs the game on a higher FPS (so he would move smaller amounts but more frequently) and those character faster who runs the game on a lower FPS (so he would move larger amounts less frequently) and in the end they would move equal distances over the same time.
Please note that it does matter what unit you use when multiplying with the delta time:
If you use millis then at 60FPS your delta would be 16.6667 ending up with 1*16.6667 = 16.6667 movement every frame. However, if you would measure your delta time in seconds then at 60FPS your delta time would be 0.016667 meaning that your character would move 0.016667 units every frame.
This is not something you should worry about, just keep it in mind.
Delta time is simply the time it takes for one frame to "dispose" of itself and then another to display on the screen. Its basically the time between frames, as you put it. From Google:
Mathematics. an incremental change in a variable.
Let's pick apart your code.
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
This line simply returns the current time in (I believe) milliseconds?
long currentTime = getTime();
int delta = (int)(currentTime - lastTime);
lastTime = getTime();
return delta;
The first line simply gets the current time. Second line then calculates delta by subtracting the current time (which is the time when the current frame was displayed) by the lastTime variable (which is the time when the last frame was displayed). Then lastTime is set to the currentTime, which is when the current frame is displayed. Its really simple when you think about it, its just the change in time between frames.

What's best way to keep a ruby process run forever?

I have to run a file.rb that make a micro-task (Insert a qwuery into a database) every second.
I have used a for loop (1..10^9) but I got a CPU usage exceed alert! So what's the best way to not waste all CPU?
The simplest way to run forever is just to loop
loop do
run_db_insert
sleep 1s
end
If it's important that you maintain a 1 Hz rate, note that the DB insert takes some amount of time, so the one-second sleep means each cycle takes dbtime+1 second and you will steadily fall behind. If the DB interaction is reliably less than a second, you can modify the sleep to adjust for the next one-second interval.
loop do
run_db_insert
sleep(Time.now.to_f.ceil - Time.now.to_f)
end
Simple loop with sleep command should do the job.
while true
# do stuff here
sleep 1 # wait one second
end

How to handle mass database manipulation every second - threading?

I have a very hard problem:
I have round about 20-50 objects, which I MUST (that is given for the problem, please don't spend time in thinking around it) put througt a logic EVERY SECOND.
The logic itself need round about 200-600 milliseconds (90% it is 200ms - 10% it is 600ms).
I try to find any solution how I can make is smaller, but there isn't. I must get an object from DB, I must have a lot of if-else and I must actual it. - Even if I reduce it to 50ms or smaller, to veriable rate of the object up to 50 will break my neck with the 1 second timer, because 50 x 50mx =2,5 second. So a tick needs longer then the tickrate should be.
So, my only, not very smart I think, idea is to open for every object an own thread and lead a mainthread for handling. So the mainthread opens x other thread. So only this opening must take unter 1 second. After it logic is used, the thread can kill itself and we all are happy, aren't we?
By given the last answers, I will explain my problem:
I try to build an auctioneer site. So I have up to 50 auctions running at the same moment - nothing special. So I need to: every single second look to the auctionlist, see if the time is 00:00:01 and if it is, bid automaticly (it's a feature, that user can create).
So: get 50 objects in a list, iterate through, check if a automatic bid is need, do it.
With 50 objects and the processing time you've given on average you are doing 12 seconds worth of processing every second. Assuming you have 4 cores, you can get this down to an execution time of 4 seconds via threading. Every second. This means that you're going to start off behind and slip further behind as time goes on.
I know you said you tried to think of a way to make it more efficient, but couldn't, but I fear you're going to have to. The problem as stated now is computationally intractable. You're either going to have to process the objects in a rotating window (so each object gets hit once every 4th cycle or so), or you need to make your processing run faster.
First: Profile, if you haven't already. Figure out what section of your code are taking time, etc. I'd go after that database - how long is the I/O of the objects from the database taking? Can you cache that I/O? (If you're manipulating the same 50 objects, don't load them every second.)
Let's address your threads idea: If you want multiple threads, don't create and destroy them every second. Create your X threads, and leave them be -- creating & destroying them are going to be expensive operations. You might find that less threads will work better - such as 1 or 2 per core, as you might be able to reduce time doing context switches.
To expand on Jonathan Leffler's comment on the question, as the OP requested: (This answer is a wiki)
Say you have these three things being auctioned, ending at the times indicated:
10 Apples - ends at 1:05:00 PM
20 Blueberries - ends at 2:00:00 PM
15 Pears - ends at 3:50:00 PM
If the current time is 1:00:00 PM, then sleep for 4 minutes, 58 seconds (since the closest item ends in 5 minutes). We use the 2 seconds then for processing - adjust that threshold as needed. Once we're done with the apples, we'll sleep for (2 PM - now() - 2s), for the blueberries.
Note that when we wake up at 1:04:58 PM to process the apples auction, we do not touch the blueberries or the pears -- we know that they're still way out in the future, so we don't care.

Resources