Current Location: Home> Latest Articles> How to Precisely Control Task Execution Time by Combining gettimeofday and sleep Functions

How to Precisely Control Task Execution Time by Combining gettimeofday and sleep Functions

gitbox 2025-06-27

1. Understanding gettimeofday and sleep

  1. gettimeofday is a standard C library function commonly used to obtain the current system time with microsecond-level precision. Its declaration is as follows:

    <span><span><span class="hljs-type">int</span></span><span> </span><span><span class="hljs-title function_">gettimeofday</span></span><span><span class="hljs-params">(<span class="hljs-keyword">struct</span></span></span><span> timeval *tv, </span><span><span class="hljs-keyword">struct</span></span><span> timezone *tz);
    </span></span>
    • tv is a timeval structure that contains seconds and microseconds;

    • tz refers to timezone information, which is usually passed as NULL since timezone details are generally not needed.

    The return value of gettimeofday is the current time in seconds and microseconds, which can be used for precise calculation of task execution time.

  2. The sleep function

    The sleep function pauses the program execution for a given number of seconds, typically used to control wait times in code. Its declaration is:

    <span><span><span class="hljs-type">unsigned</span></span><span> </span><span><span class="hljs-type">int</span></span><span> </span><span><span class="hljs-title function_">sleep</span></span><span><span class="hljs-params">(<span class="hljs-type">unsigned</span></span></span><span> </span><span><span class="hljs-type">int</span></span><span> seconds);
    </span></span>

    However, sleep only provides second-level precision. For higher precision time control, the usleep function can be used, which allows specifying microseconds.


2. How to Combine gettimeofday and sleep to Precisely Control Execution Time

Suppose you need to precisely control the execution time of a task in a program, such as running the task repeatedly at fixed time intervals, while ensuring the execution duration is neither too long nor too short. You can use gettimeofday to get the current time and combine it with the sleep function to adjust the interval between each execution.

  1. Get the current time

    First, call gettimeofday to retrieve the current system time. This gives you the exact time point when the task starts executing.

  2. Calculate the target time

    Assuming the task should run every 100 milliseconds. After obtaining the start time, calculate the target time for the next execution. The target time equals the current time plus the task interval.

  3. Wait until the target time is reached

    After calculating the target time, compute the difference between the current time and the target time, then use sleep or usleep to wait precisely. This helps avoid tasks running too long or too short.

  4. Control task accuracy

    For even more precise control, check the current time after the task completes to ensure the interval meets the requirements.

Below is an example demonstrating how to use gettimeofday and sleep to control task execution timing:

<span><span><span class="hljs-meta">&lt;?php</span></span><span>
</span><span><span class="hljs-comment">// Set the interval for each task execution (seconds and microseconds)</span></span>
</span><span><span class="hljs-variable">$interval_sec</span></span> = </span><span><span class="hljs-number">0</span></span>;      </span><span><span class="hljs-comment">// seconds</span></span>
</span><span><span class="hljs-variable">$interval_usec</span></span> = </span><span><span class="hljs-number">100000</span></span>; </span><span><span class="hljs-comment">// microseconds, 100 milliseconds</span></span>
<p></span>// Get the current time<br>
function getCurrentTime() {<br>
</span>$time = </span>gettimeofday();<br>
return $time['sec'] * 1000000 + $time['usec']; // Return current time in microseconds<br>
}<br>
</span></p>
<p></span>// Calculate the target execution time for the task<br>
function getTargetTime($interval_sec, $interval_usec) {<br>
</span>$current_time = </span>getCurrentTime();<br>
return $current_time + $interval_sec * 1000000 + $interval_usec;<br>
}<br>
</span></p>
<p></span>// Simulate a timed task<br>
function performTask() {<br>
</span>// Simulate task execution (e.g., processing data, API calls, etc.)<br>
echo "Task performed at: " . date("Y-m-d H:i:s") . "\n";<br>
}<br>
</span></p>
<p></span>// Main program<br>
while (true) {<br>
// Get current time<br>
$current_time = getCurrentTime();</p>
</span><span><span class="hljs-variable">$target_time</span> = </span><span><span class="hljs-title function_ invoke__">getTargetTime</span>($interval_sec, $interval_usec);

</span><span><span class="hljs-comment">// Perform the task</span>
</span><span><span class="hljs-title function_ invoke__">performTask</span>();

</span><span><span class="hljs-comment">// Calculate sleep duration</span>
</span><span><span class="hljs-variable">$sleep_time</span> = </span><span>$target_time - </span><span><span class="hljs-title function_ invoke__">getCurrentTime</span>();

</span><span><span class="hljs-comment">// If task executed quickly, use usleep for precise waiting</span>
</span><span><span class="hljs-keyword">if</span> ($sleep_time > 0) {
    </span><span><span class="hljs-title function_ invoke__">usleep</span>($sleep_time);  </span><span><span class="hljs-comment">// Wait until target time is reached
</span>}

}
?>

In this example, the task runs every 100 milliseconds. The gettimeofday function is used to get the current time, the target time is calculated, and usleep is used for precise waiting. This approach ensures accurate control of task execution, minimizing timing deviations caused by system scheduling or other factors.