zoukankan      html  css  js  c++  java
  • linux 统计 程序 运行时间

    测试 代码运行时间

    linux 中的 <sys/time.h> 中 有个函数可以获取当前时间,精确到 微秒 ---->  gettimeofday()

    复制代码
     1 #include <sys/time.h> 
          // int gettimeofday(struct timeval *tv, struct timezone *tz); 2 /********************************************* 3 * struct timeval 4 * { 5 * time_t tv_sec; // seconds 6 * suseconds_t tv_usec; // microseconds:微秒 10^(-6)s, 这里的 tv_sec 用的是 微秒 7 * // millisecond :毫秒 10^(-3)s 8 * } 9 ********************************************** 10 * struct timezone 11 * { 12 * int tz_minuteswest; // minutes west of Greenwich 13 * int tz_dsttime; // type of DST correction 14 * } 15 **********************************************/
    复制代码

    使用时,定义两个 struct timeval  变量(通常 gettimeofday() 的第二个参数 设为 NULL),分别保存 代码测试 前后的时刻,最后相减,即可获取 代码运行时间 (可转换为自己需要的时间)。

    复制代码
     1 #include <stdio.h>
     2 #include <sys/time.h> // for gettimeofday()
     3 #include <string.h>   // for memset()
     4 
     5 int main()
     6 {
     7     int i = 10000000;
     8     struct timeval start, end;  // define 2 struct timeval variables
     9 
    10     //-------------------------
    11     gettimeofday(&start, NULL); // get the beginning time
    12     //-------------------------
    13     
    14     // test code
    15     while(i)
    16     {
    17         i--;
    18     }
    19 
    20     //-------------------------
    21     gettimeofday(&end, NULL);  // get the end time
    22     //-------------------------
    23     
    24     long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
    25     printf("total time is %lld us
    ", total_time);
    26     total_time /= 1000; // get the run time by millisecond
    27     printf("total time is %lld ms
    ", total_time);
    28 }

    测试结果:(CentOS 6.5, gcc 4.4.7)
    total time is 49658 us
    total time is 49 ms
  • 相关阅读:
    windows live sync, mesh, skydrive
    忘记SQL SERVER密码的解决
    处理ObjectDataSource调用中DAL层中的异常
    C#中获取应用程序路径的方法(集合)
    datatable复制一行数据到本表
    [Yii Framework] yii中如何在查询的时候使用数据库函数
    [Yii Framework] yii的路由配置
    [Yii Framework] 已经定义的命名空间常量
    [Yii Framework] yii中关于filter
    [Yii Framework] yii中如何不加载layout
  • 原文地址:https://www.cnblogs.com/spinsoft/p/3767549.html
Copyright © 2011-2022 走看看