lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Time Delay function

Wed Dec 25, 2013 2:57 am

Code: Select all

//=====================================================================//
 /*
 * delay:
 *	Wait for some number of milliseconds
 *********************************************************************************
 */


void delay (unsigned int howLong)
{
  struct timespec sleeper, dummy ;

  sleeper.tv_sec  = (time_t)(howLong / 1000) ;
  sleeper.tv_nsec = (long)(howLong % 1000) * 1000000 ;

  nanosleep (&sleeper, &dummy) ;
}
let say we delay 50 milliseconds.
sleeper.tv_sec=(time_t)(50/1000); that's equal to 0.05 seconds
sleeper.tv_nsec=(long)(50%1000)*1000000 that's equal to 50*1000000= 500,000,000
or 5 nanoseconds.


questions, why does sleeper needs both second and nanosecond fields? Seem like they are holding to same values.

second question why does tv_sec uses a divide function / and tv_nsec uses a modulus ,% function?

User avatar
AndyD
Posts: 2334
Joined: Sat Jan 21, 2012 8:13 am
Location: Melbourne, Australia
Contact: Website

Re: Time Delay function

Wed Dec 25, 2013 4:19 am

If we have a delay of 50 milliseconds

sleeper.tv_sec = (time_t)(50/1000); that equals zero as time_t is an integer value, not floating point.
sleeper.tv_nsec = (long)(50%1000) * 1000000; that equals 50 * 1000000 = 50,000,000 nanoseconds or 50 milliseconds.

There are 1,000,000,000 nanoseconds in a second, 1,000,000 microseconds in a second and 1,000 milliseconds in a second.
lilzz wrote:questions, why does sleeper needs both second and nanosecond fields? Seem like they are holding to same values.
As stated above tv_sec is not a floating point value it is an integer. These is no way to represent a fraction of a second in tv_sec.
lilzz wrote:second question why does tv_sec uses a divide function / and tv_nsec uses a modulus ,% function?
In integer division the remainder is discarded. The modulus operator returns the remainder from the division. The parameter howlong to the delay function is in milliseconds, the nanosleep function requires the sleep time to be set in two parts, seconds and fraction of one second (i.e. nanoseconds). All the code is doing is converting howlong into seconds and fractions of a second.

Return to “C/C++”