I'm sending packets from a sender thread to a receiver thread. To control the send rate (packets per second), I calculate the time I need to wait before sending the next packet to maintain a certain send rate.
Let's say the time needed to wait was calculated to be 100 microseconds.
(double)(clock() - start)/CLOCKS_PER_SEC;
usleep(100);
(double)(clock() - start)/CLOCKS_PER_SEC;
in step 3, when I check what time it is only 50 microseconds have passed (I checked the return value of usleep
and confirmed it is returning 0).
Why is this? shouldn't it be sleeping for at least 100 microseconds? Or is there a different sleep function I should be using with clock()
? Thanks for any suggestions
答案 0 :(得分:2)
The clock
function is defined to give you elapsed process time, not the wall clock (which unfortunately the Windows Visual Studio runtime library gives you). If your process isn't actually running, because it's sleeping, then no processor time will pass
How to get the walltime depends on your platform, but on POSIX (like Linux, OSX or the BSD variants) the recommended way is clock_gettime
with the CLOCK_REALTIME
clock.