计算程序运行的时间

来源:互联网 发布:电信网络电视多少钱 编辑:程序博客网 时间:2024/05/01 04:51

      通常我们在写程序后常常需要知道某一段代码或者这个程序运行了多长时间,这样有利于我们计算程序的效率,这篇文章讲述的就是这个问题。

      首先,我们需要知道一个结构:

struct timeval {               time_t      tv_sec;     /* seconds */               suseconds_t tv_usec;    /* microseconds */           };

      这个结构代表的是时间值,我们利用函数 gettimeofday ,可以对其进行填充,其中的第一个字段代表的是秒,第二个字段代表的是微妙,也就是百万分之一秒。通常我们会这样做:

      struct timeval tv;

      gettimeofday(&tv, NULL);

      第一个参数是时间结构的指针,第二个参数代表的是时区。通常,设为NULL就可以了。这里,tv填充的其实是现在的时间,那么,在程序中,我们通过两次调用这个函数,之后,再用后值减去前值就可以得到程序运行的时间了。

      下面给出一段实例程序:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/time.h>void get_time_sub(struct timeval *in, struct timeval *out);int main(int argc, char **argv, char **environ){int i;struct timeval in;struct timeval out;memset(&in, 0, sizeof(in));memset(&out, 0, sizeof(out));gettimeofday(&out, NULL);for(i = 0; i != 1000000; i++){}gettimeofday(&in, NULL);get_time_sub(&in, &out);printf("time is %ld us\n", (in.tv_sec * 1000000 + in.tv_usec));}void get_time_sub(struct timeval *in, struct timeval *out){if (in -> tv_usec -= out -> tv_usec < 0){in -> tv_sec -= 1;in -> tv_usec += 1000000;}in -> tv_sec -= out -> tv_sec;}