I call this function in my centos 7 server.
I find std::this_thread::sleep_for(chrono::nanoseconds(1))
actually sleep for one ms, Is there any explanation? I think it may be caused by os setting?
I call this function in my centos 7 server.
I find std::this_thread::sleep_for(chrono::nanoseconds(1))
actually sleep for one ms, Is there any explanation? I think it may be caused by os setting?
3
Answers
From sleep_for documentation, you can see that:
The most likely cause is that your process scheduler kicks out the sleeping thread and doesn’t reschedule it for a millisecond.
Let’s first check what guarantees the specification gives you (quotes from the latest daft of the C++ standard):
So, it is expected for the slept time to be longer than Dt given as the argument.
Assuming your test was correct, we can use it to calculate that Di+Dm was about a millisecond on your system with your hardware in that particular execution.
No, not in standard C++ for on all systems.
It may potentially be possible on a real-time capable system. See the documentation of the system that you are targeting.
You’ve got the question you asked covered by the other answers, but you also asked a question in the comments:
Instead of calling
sleep_for
, yielding the thread’s execution slot, you could busy-sleep. That is, loop until a certain amount of time has passed. It’ll often get more accurate results at the cost of making that CPU thread unusable for doing anything else.Here’s one example with a function called
busy_sleep()
:Demo
Note: This was updated after it was accepted since I noticed that the overhead calculation could sometimes get terribly wrong. The updated example should be less fragile.