linux 定时器的使用

方法一

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值