定时器的设置:

#include <signal.h>
  #include <sys/time.h>
  #include <stdio.h>int main(){
    signal(SIGALRM,signal_hander);                      //设置SIGALRM信号处理函数
    set_timer(); //调用这个函数设置计时器的值             //设置定时时间,启动定时器,时间到就会产生SIGALRM信号
                     //alarm(4);//也可设置定时时间
                     pause();//挂起进程  ,定时时间到,时钟发送一个SIGALRM信号给进程,执行signal_hander,后继续执行pause后代码
                                           //注意:如果没有处理函数,进程将被杀死      printf("now we can go on !");
}
   static struct itimerval oldtv;
   void set_timer( ){
  struct itimerval itv;	
  itv.it_interval.tv_sec = 10; //初始间隔
  itv.it_interval.tv_usec=0;
  itv.it_value.tv_sec=10;      //重复间隔
  itv.it_value.tv_usec=0;
  setitimer(ITIMER_REAL, &itv, &oldtv);
   }
  void signal_hander(){
    stateM_handleEvent( &m, &(struct event){ Event_keyboard,(void *)(intptr_t)'s' } );
  }

 计时器:

  统计程序运行时间

  Linux/Unix环境下计算C程序运行时间可以通过clock, times, gettimeofday, getrusage来实现。

  clock:ANSI C的标准库函数,关于这个函数需要说明几点:

    首先,它返回的是CPU耗费在本程序上的时间。也就是说,途中sleep的话,由于CPU资源被释放,那段时间将不被计算在内。

    其次,得到的返回值其实就是耗费在本程序上的CPU时间片的数量,也就是Clock Tick的值。该值必须除以CLOCKS_PER_SEC这个宏值,才能最后得到ss.mmnn格式的运行时间。

                  在POSIX兼容系统中,CLOCKS_PER_SEC的值为1,000,000的,也就是1MHz。

    最后,使用这个函数能达到的精度大约为10ms。

  times:times的用法基本和clock类似,同样是取得CPU时间片的数量,所不同的是要除以的时间单位值为sysconf(_SC_CLK_TCK)。

  gettimeofday:用gettimeofday直接提取硬件时钟进行运算,得到的结果的精度相比前两种方法提高了很多。

    但是也正由于它提取硬件时钟的原因,这个方法只能计算程序开始时间和结束时间的差值。而此时系统中如果在运行其他的后台程序,可能会影响到最终结果的值。如果后台繁忙,

    系统dispatch过多的话,并不能完全真实反映被测量函数的运行时间。

  getrusage:  getrusage得到的是程序对系统资源的占用信息。只要指定了RUSAGE_SELF,就可以得到程序本身运行所占用的系统时间。可以说是精度最高的测量方法了。

高精度测试的话,getrusage和gettimeofday都可以选择。需要长时间测试的话,clock也是不错的,尤其是考虑到它的通用性。

 

 clock使用:

#include<sys/time.h>
  int timer;
  clock_t start, end;
  start=clock();
  end=clock(); 
  timer=(end-start)/CLOCKS_PER_SEC>3;

本人首先接触的是gettimeofday,下边详细介绍这个函数的使用方法:

  1. 包含头文件sys/time.h.

  2.定义两个结构体 struct  timeval  start、struct  timeval  end及记录时间的变量timer.

  3. 将gettimeofday(&start,NULL)放在需要测的代码的开始部分,将gettimeofday(&end,NULL)放在需要测的代码的结束部分.

  4.语句timer = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec可以使timer记录代码运行时间(时间单位为us).

  5.printf("timer = %ld",timer) 打印出timer的值.

示例程序:

#include <stdio.h>
#include <sys/time.h>
int main()
{
   struct  timeval  start;
   struct  timeval  end;
   unsigned long timer;   gettimeofday(&start,NULL);
   printf("hello world!\n");
   gettimeofday(&end,NULL);
   timer = 1000000 * (end.tv_sec-start.tv_sec)+ end.tv_usec-start.tv_usec;
   printf("timer = %ld us\n",timer);
   return 0;
}

 在这里说明一下包含的头文件#include<time.h>和#include<sys/time.h>的区别:

  time.h 是ISO C99 标准日期时间头文件,参考http://www.cplusplus.com/reference/ctime/

  sys/time.h 是Linux 系统的日期时间头文件,参考http://pubs.opengroup.org/onlinepubs/7908799/xsh/systime.h.html

  sys/time.h 通常会包含include<time.h>

即:time.h既然是c库函数,那么在具体的平台上,就就可以依靠平台而实现,所以看上去是与平台无关的,谁都可以调用.

       而 sys/time.h 只是在linux系统上可以调用。

 

reference:

https://www.linuxidc.com/Linux/2013-01/78086.htm