What is the use of tim.tv_sec
and tim.tv_nsec
in the following?
How can I sleep execution for 500000
microseconds?
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec tim, tim2;
tim.tv_sec = 1;
tim.tv_nsec = 500;
if(nanosleep(&tim , &tim2) < 0 )
{
printf("Nano sleep system call failed \n");
return -1;
}
printf("Nano sleep successfull \n");
return 0;
}
POSIX 7
First find the function: http://pubs.opengroup.org/onlinepubs/9699919799/functions/nanosleep.html
That contains a link to a
time.h
, which as a header should be where structs are defined:man 2 nanosleep
Pseudo-official glibc docs which you should always check for syscalls:
Half a second is 500,000,000 nanoseconds, so your code should read:
As things stand, you code is sleeping for 1.0000005s (1s + 500ns).
This worked for me ....
500000 microseconds are 500000000 nanoseconds. You only wait for 500 ns = 0.5 µs.
tv_nsec
is the sleep time in nanoseconds. 500000us = 500000000ns, so you want:I usually use some #define and constants to make the calculation easy:
Hence my code would look like this: