I'm writing a simple program, which checks if elapsed time is more than 1 seconds. I take start time with a clock_gettime(), then I call sleep(5), take new time and I check if the difference is bigger than 1; I sleep 5 seconds, then it should be greater than 5, but my program prints a strange result.
this is the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main()
{
struct timespec tv1,tv3,expected;
struct timespec nano1;
tv1.tv_nsec = 0;
tv3.tv_nsec = 0;
expected.tv_nsec = 400000;
if(clock_gettime(CLOCK_MONOTONIC,&tv3) == -1){
perror(NULL);
}
sleep(5);
if(clock_gettime(CLOCK_MONOTONIC,&tv1) == -1){
perror(NULL);
}
long nsec = tv1.tv_nsec - tv3.tv_nsec;
if(nsec>expected.tv_nsec){
printf("nsec runned: %ld nsec timeout: %ld\n",nsec,expected.tv_nsec);
}
printf("elapsed nanoseconds: %ld\n",nsec);
if((nsec>expected.tv_nsec))
printf("expired timer\n");
else
printf("not expired timer\n");
exit(EXIT_SUCCESS);
}
Output of my program is:
"elapsed nanoseconds: 145130" and "not expired timeout"
Where is the problem?
You are using the nsec (nanoseconds) portion of the timestamps and totally ignoring the sec (seconds) part. Those timestamps are composed of two integers, and to get any meaning from them you need both.
Ref: http://en.cppreference.com/w/c/chrono/timespec