实现精准定时器需要使用操作系统提供的高精度计时器,Linux中提供了POSIX定时器,可以满足微秒级别的需求。下面是一个简单的C/C++代码示例:
源码:
#include <stdio.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <time.h>
struct timeval tv;
//gettimeofday(&tv,NULL);
//printf("s:%ld\n",tv.tv_sec); //秒
//printf("ms:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
//printf("us:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
static int count = 0;
void timer_handler(int signum) {
if(count % 999 == 0) //1000次打印一次时间
{
gettimeofday(&tv,NULL);
printf("ms:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
}
printf("%d ",count++);
}
int main(void) {
timer_t timerid;
struct sigevent sev;
struct itimerspec its;
struct sigaction sa;
// 设置定时器信号处理函数
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = timer_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIGRTMIN, &sa, NULL);
// 创建定时器
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGRTMIN;
sev.sigev_value.sival_ptr = &timerid;
timer_create(CLOCK_REALTIME, &sev, &timerid);
// 设置定时器参数
its.it_value.tv_sec = 1; // 初始延时1秒
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 0; // 定时周期为100微秒
its.it_interval.tv_nsec = 100000;
timer_settime(timerid, 0, &its, NULL);
// 循环等待定时器信号
while (1) {
sleep(1);
}
return 0;
}
编译:
gcc demo.c -lrt
使用了POSIX定时器创建了一个精准定时器,定时周期为100微秒。在定时器信号处理函数中输出了定时器到期的信息。需要注意的是,该代码使用了Linux特有的实时信号SIGRTMIN,如果需要移植到其他平台上需要进行相应的修改。