zoukankan      html  css  js  c++  java
  • c语言计算程序运行时间的方法

    1. 有时候我们要计算程序执行的时间.比如我们要对算法进行时间分析,这个时候可以使用下面这个函数.

    精确到us。
     
    #include <sys/time.h> 
    int gettimeofday(struct timeval *tv,struct timezone *tz); 
    strut timeval { 
    long tv_sec; /* 秒数 */ 
    long tv_usec; /* 微秒数 */ 
    }; 
    gettimeofday将时间保存在结构tv之中.tz一般我们使用NULL来代替. 
    #include <sys/time.h< 
    #include <stdio.h< 
    #include <math.h< 
    void function() 
    { 
    unsigned int i,j; 
    double y; 
    for(i=0;i<1000;i++) 
    for(j=0;j<1000;j++) 
    y=sin((double)i); 
    } 
    main() 
    { 
    struct timeval tpstart,tpend; 
    float timeuse; 
    gettimeofday(&tpstart,NULL); 
    function(); 
    gettimeofday(&tpend,NULL); 
    timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+ 
    tpend.tv_usec-tpstart.tv_usec; 
    timeuse/=1000000; 
    printf("Used Time:%f\n",timeuse); 
    exit(0); 
          }

    这个程序输出函数的执行时间,我们可以使用这个来进行系统性能的测试,或者是函数算法的效率分析.在我机器上的一个输出结果是: Used Time:0.556070

    2.第二种是我自己经常用的,就是:

    在执行程序前,加time,如:输入time./abc ,精确到ms。

    3. clock函数(精确到1/CLOCKS_PER_SEC秒,毫秒级)

    #include   <iostream> 
      #include   <ctime> 
      using   namespace   std; 
      int   max(int   x,int   y) 
      { 
            return   (x>y)?x:y; 
      } 
      int   main() 
      { 
              const   double   begin=clock(); 
      for(int   i=10000;i>0;i--) 
      for(int   j=10000;j>0;j--) 
      max(i,j); 
              const   double   end=

    clock(); 

      cout   <<begin<<"     "<<end; 
      return   0; 
      }

  • 相关阅读:
    js获取当前时间
    jQuery动画
    label用js,jquery取值赋值,以及怎么在后台取值
    jquer 事件,选择器,dom操作
    linq分页组合查询
    linq的简单增删改查
    内置对象session ,cookic,Application,ViewState
    listview控件及其与数据库的连接
    Mybatis 学习
    UML类图的6中关系
  • 原文地址:https://www.cnblogs.com/feisky/p/1624024.html
Copyright © 2011-2022 走看看