Https://www.cnblogs.com/cobbliu/p/3627061.html
A timing function for Linux to get the current time:
- Time (2)/time_t (SEC)
- Ftime (3)/struct TIMEB (ms)
- Gettimeofday (2)/struct Timeval (μs)
- Clock_gettime (2)/struct Timespec (nanoseconds)
- Gmtime/localtime/timegm/mktime/strftime/struct TM (These are independent of the current time)
A timer function that allows a program to wait for a period of time or schedule a task:
- Sleep
- Alarm
- Getitimer/setitimer
- Timer_create/timer_settime/timer_gettime/timer_delete
- Timerfd_create/timerfd_gettime/timerfd_settime
- Conditional variable PTHREAD_COND_TIMEDWAIT implementation
- IO multiplexing Select, Epoll implementation
In general, get the current time commonly used gettimerofday, because its precision is 1us, and on the x86 platform it is user-state implementation, there is no system calls and context switching overhead.
In the timer function:
- Sleep/alarm in the implementation of the possibility of using the signal SIGALRM, in multi-threaded program processing signal is a rather troublesome thing, should try to avoid.
- Nanosleep and Clock_nanosleep are thread-safe, but in non-blocking network programming, there is absolutely no way to wait for a while for a thread to hang, and the program will lose its response. The correct approach is to register a time callback function.
- Getitimer and Timer_create also use signals to deliver timeouts, which can also be problematic in multithreaded programs. Timer_create can specify whether the receiver of the signal is a process or a thread, which is a step forward, but what can be done in the signal processing function (signal handler) is quite limited.
- Timerfd_create the time into a file descriptor, the "file" becomes readable at the moment the timer times out, making it easy to integrate into the Select/poll framework to handle IO events and timeout events in a unified manner.
- Using SELECT, the timeout of epoll to realize timing function, their disadvantage is that the timing accuracy is only milliseconds, far lower than the timing accuracy of timerfd_settime.
Linux Time and Timer ZZ