Article Title: Real-Time timer posix_timer in Linux. Linux is a technology channel of the IT lab in China. Includes basic categories such as desktop applications, Linux system management, kernel research, embedded systems, and open source.
In fact, there is a high-precision timer in Linux, namely posix_timer. in principle, you can also use the rdtsc command during frequency conversion, because we also know the CPU frequency, and the kernel is also known during frequency conversion.
The following is an example of my timer_create. The rt library must be added during compilation. This is the linux realtime Library:
Gcc-o test. c
# Include # Include # Include # Include # Include
# Define rdtsc (low, high) _ asm _ volatile _ ("rdtsc": "= a" (low), "= d" (high ))
Timer_t tt;
Void handler (int sig, siginfo_t * extra, void * cruft) ...{ Static last_ I = 0; Unsigned int I, j; Rdtsc (I, j ); Printf ("time: % u, % u, [% u] % uHZ", j, I, i-last_ I, (i-last_ I) * 10/1000000 ); Last_ I = I; }
Int main () ...{ Int I = 0; Sigset_t sigset;
Sigfillset (& sigset ); Sigdelset (& sigset, SIGRTMIN ); Sigprocmask (SIG_SETMASK, & sigset, NULL );
Struct sigaction sa; Sigfillset (& sa. sa_mask ); Sa. sa_flags = SA_SIGINFO; Sa. sa_sigaction = handler;
If (sigaction (SIGRTMIN, & sa, NULL) <0) ...{ Perror ("sigaction failed "); Exit (-1 ); }
Struct sigevent timer_event; Struct itimerspec timer;
Timer. it_interval. TV _sec = 0; Timer. it_interval. TV _nsec = 100*1000*1000; Timer. it_value = timer. it_interval;
Timer_event.sigev_notify = SIGEV_SIGNAL; Timer_event.sigev_signo = SIGRTMIN; Timer_event.sigev_value.sival_ptr = (void *) & tt;
If (timer_create (CLOCK_REALTIME, & timer_event, & tt) <0) ...{ Perror ("timer_create failed "); Exit (-1 ); }
If (timer_settime (tt, 0, & timer, NULL) <0) ...{ Perror ("timer_settime failed "); Exit (-1 ); }
While (I ++ <10) ...{ Pause (); }
Return 0; } |
Output result:
Time: 166081,193 4350847, [1934350847] 2163 HZ Time: 166081,212 0528291, [186177444] 1861 HZ Time: 166081,230 6679576, [186151285] 1861 HZ Time: 166081,249 4695630, [188016054] 1880 HZ Time: 166081,268 0865389, [186169759] 1861 HZ Time: 166081,286 7018473, [186153084] 1861 HZ Time: 166081,305 3152230, [186133757] 1861 HZ Time: 166081,323 9309935, [186157705] 1861 HZ Time: 166081,342 5467261, [186157326] 1861 HZ Time: 166081,361 1639266, [186172005] 1861 HZ |