Can I pass a timeval struct as the argument for a sleep function? I want to do this since the timeval struct can get very precise, since you can control the microseconds and I would like to sleep for a certain amount of microseconds. Can I do this?
Asked
Active
Viewed 454 times
0
-
7If your question really is "can I pass a timeval as argument to sleep", then the answer is "no, you can't". If your question is "how to delay execution with microsecond resolution in C", then the answer is "use `nanosleep`". Please do not ask XY questions. – KamilCuk Apr 21 '20 at 21:57
-
Does this answer your question? [Is there an alternative sleep function in C to milliseconds?](https://stackoverflow.com/questions/1157209/is-there-an-alternative-sleep-function-in-c-to-milliseconds) – KamilCuk Apr 21 '20 at 21:59
-
1Most POSIX sleep functions are always noisy, so if you need a very precise amount of delay you may need a low-level OS function. – tadman Apr 21 '20 at 22:02
-
Even if you do tell it how long to sleep, all you're really telling it is at least how long to sleep until it is permitted to wake. The OS/Scheduler is not required to wake it the moment the time has elapsed. – Christian Gibbons Apr 21 '20 at 22:10
1 Answers
1
You could do something like:
struct timeval {long tv_sec; long tv_usec;};
struct timezone {int tz_minuteswest; int tz_dsttime; };
struct timeval tp;
struct timezone tzp;
int i;
i = gettimeofday(&tp,&tzp);
And using that you can implement a delay function. Please see this example.
However if you want a precise delay you could use functions that enable you to get more precise delay such as nanosleep()
struct timespec tim, tim2;
tim.tv_sec = 1;
tim.tv_nsec = 1000000000L; //1,000,000,000 nanoseconds = 1 second
nanosleep(&tim , &tim2);
/*code after 1 second sleep*/

BSMP
- 4,596
- 8
- 33
- 44