方法一
rtc是linux系统中的一个时间设备,可以open打开,通过ioctl设置频率,然后就可以进行循环read操作,每次read的耗时是(1/频率 单位:秒)。精度较高,每10秒误差1ms
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <linux/rtc.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int main(int argc, char* argv[])
{
unsigned long i = 0;
unsigned long data = 0;
int retval = 0;
int fd = open ("/dev/rtc", O_RDONLY);
struct timeval tv;
if(fd < 0)
{
perror("open");
exit(errno);
}
printf("opened.\n");
/*Set the freq as 2Hz*/
//1秒/2Hz = 500,定时500ms
//频率范围2~8192,只能是2的次幂
if(ioctl(fd, RTC_IRQP_SET, 2 ) < 0)
{
perror("ioctl(RTC_IRQP_SET)");
close(fd);
exit(errno);
}
if(ioctl(fd, RTC_PIE_ON, 0) < 0)
{
perror("ioctl(RTC_PIE_ON)");
close(fd);
exit(errno);
}
printf("start counting...\n");
while(1)
{
if(read(fd, &data, sizeof(unsigned long)) < 0)
{
perror("read");
close(fd);
exit(errno);
}
gettimeofday( &tv , 0 );
printf("[%d]timer\n" , tv.tv_sec * 1000 + tv.tv_usec/1000);
}
ioctl(fd, RTC_PIE_OFF, 0);
close(fd);
return 0;
}
方法二
可以直接用usleep(500000)定时500ms,但精度较差。每500ms误差1ms
#include <stdio.h>
#include <sys/time.h>
int main(int argc, char *argv[])
{
struct timeval tv;
while(1){
usleep(500000);
gettimeofday( &tv , 0 );
printf("[%d]timer\n" , tv.tv_sec * 1000 + tv.tv_usec/1000);
}
return 0;
}