最近项目中需要时用nuc970内部定时器来对程序运行时间做精确计时。需要精度至少到0.1ms。但是我按照如下代码测试nuc970的定时器发现同样程序, 每次测试出来的运行时间是不一样的。求教这是为什么 ?linux系统调度的原因么?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/select.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include "nuc970-etimer.h"
int main(int argc, char **argv){
    int fd_timer;
    int ret,j=0,cnt;
    int ii,jj,kk;
    char *dev = "/dev/etimer0";
    int timeout = 1000;  // base : 1ms 
    fd_timer = open(dev,O_RDWR);
    if(fd_timer < 0)
        printf("open etimer error\n");
    ioctl(fd_timer, ETMR_IOC_CLKHXT, NULL);
    ioctl(fd_timer, ETMR_IOC_PERIODIC, &timeout); 
    for(j=0;j<20;j++){
        read(fd_timer, &cnt, sizeof(cnt));
        printf("startime = %u\n",cnt);
        /*测试运行代码*/
        for(ii=0;ii<100;ii++)    
            for(jj = 0; jj < 200; jj++);            
                
        read(fd_timer, &cnt, sizeof(cnt));
        printf("endtime  = %u\n\n",cnt);
    }
    
    ioctl(fd_timer, ETMR_IOC_STOP, NULL);
    
}运行结果如下
startime = 1
endtime  = 4
startime = 8
endtime  = 12
startime = 15
endtime  = 19
startime = 20
endtime  = 21
startime = 22
endtime  = 23
startime = 24
endtime  = 25
startime = 26
endtime  = 27
startime = 28
endtime  = 29
startime = 30
endtime  = 31
startime = 32
endtime  = 33
startime = 34
endtime  = 35
startime = 36
endtime  = 37
startime = 38
endtime  = 40
startime = 44
endtime  = 48
startime = 49
endtime  = 50
startime = 51
endtime  = 52
startime = 53
endtime  = 54
startime = 55
endtime  = 56
startime = 57
endtime  = 58
startime = 59
endtime  = 60离线
在应用层恐怕不准吧?
离线
我的测试结果,显示在Linux应用层可能是由于任务调度的原因,每次执行的时间是不一样的,但是同样一段程序的执行时间大体一致。上面的配置是1ms的配置。误差都在1ms之内,对于我的项目来说暂时可以接受。
离线