[PAT Advanced Level]1032. Sharing (25)

2014-11-24 02:00:45 · 作者: · 浏览: 1
通常我们在写程序后常常需要知道某一段代码或者这个程序运行了多长时间,这样有利于我们计算程序的效率,这篇文章讲述的就是这个问题。
首先,我们需要知道一个结构:
struct timeva l {  
               time_t      tv_sec;     /* seconds */  
               suseconds_t tv_usec;    /* microseconds */  
           };  

这个结构代表的是时间值,我们利用函数 gettimeofday ,可以对其进行填充,其中的第一个字段代表的是秒,第二个字段代表的是微妙,也就是百万分之一秒。通常我们会这样做:
struct timeva l tv;
gettimeofday(&tv, NULL);
第一个参数是时间结构的指针,第二个参数代表的是时区。通常,设为NULL就可以了。这里,tv填充的其实是现在的时间,那么,在程序中,我们通过两次调用这个函数,之后,再用后值减去前值就可以得到程序运行的时间了。
下面给出一段实例程序:
#include   
#include   
#include   
#include   
  
void get_time_sub(struct timeva l *in, struct timeva l *out);  
  
int main(int argc, char **argv, char **environ)  
{  
    int i;  
    struct timeva l in;  
    struct timeva l 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 timeva l *in, struct timeva l *out)  
{  
    if (in -> tv_usec -= out -> tv_usec < 0)  
    {  
        in -> tv_sec -= 1;  
        in -> tv_usec += 1000000;  
    }  
    in -> tv_sec -= out -> tv_sec;  
}