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\n", total_time);
    26     total_time /= 1000; // get the run time by millisecond
    27     printf("total time is %lld ms\n", total_time);
    28 }

    测试结果:(CentOS 6.5, gcc 4.4.7)
    total time is 49658 us
    total time is 49 ms
  • 相关阅读:
    Spring AOP概念理解
    五分钟快速掌握RPC原理及实现
    Linux常用命令汇总
    一致性哈希算法原理
    RPC原理及实现
    IO设计模式:Reactor和Proactor对比
    到底什么时候该使用MQ?
    eclipse查看一个方法被谁引用(调用)的快捷键四种方式
    maven build pulgin
    VSCode 常用setiings.json设置
  • 原文地址:https://www.cnblogs.com/molly/p/3764351.html
Copyright © 2011-2022 走看看