zoukankan      html  css  js  c++  java
  • 函数运行时间计算方法

    在写代码中,有时候我们需要评估某段代码或者函数的执行时间;方法就是在该段代码或者函数前面,记录一个时间T1,在代码段或函数后面记录时间T2,那其运行时间就是T2-T1;

    就是简单的减法!!!

    那具体的实现方法呢?我这里有两个,给大家参考:

    一,clock();

    clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t;头文件:time.h;

    typedef long clock_t;可见clock_t为长整型;

    在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,其定义如下:
    #define CLOCKS_PER_SEC ((clock_t)1000)
    例子:
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main(void)
    {
    long i = 10000000L;
    clock_t start, finish;
    double duration;
    /* 测量一个事件持续的时间*/
    printf( "Time to do %ld empty loops is ", i) ;
    start = clock();
    while( i-- );
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;
    printf( "%f seconds ", duration );
    system("pause");
    }
     
    二,另一种形式就是timeval结构体,定义如下:
    struct timeval
    {
    time_t tv_sec; /* Seconds. */
    suseconds_t tv_usec; /* Microseconds. */
    };
    例子:
    #include <stdio.h>
    #include <sys/time.h>
    #include <time.h>

    int main(int argc, char * argv[])
    {
    struct timeval tv; //定义
    while(1){
    gettimeofday(&tv, NULL); //获取时间
    printf("time %u:%u ", tv.tv_sec, tv.tv_usec);
    sleep(2);
    }
    return 0;
    }
     
    两种方法的区别:
    1,若是粗略的计算,都可以使用;
    2,区别在于定义上:clock的最小精度为毫秒(ms);使用的节拍来定义;
    timeval精确到微秒(us),获取的是系统时间,而且还有秒;
     
    具体的使用,根据实际情况来决定!祝大家的代码中bug越来越少。
     
     
     
     
     
  • 相关阅读:
    页面上传图片后立即预览
    MySQL用户管理
    两种方式实现java生成Excel
    总结个关于MySQL数据库的问题
    Properties操作指南
    Python笔记之不可不练
    Python笔记之不可不知
    SpringMVC一路总结(三)
    SpringMVC一路总结(二)
    SpringMVC一路总结(一)
  • 原文地址:https://www.cnblogs.com/cyc2009/p/6421892.html
Copyright © 2011-2022 走看看