zoukankan      html  css  js  c++  java
  • (转)C/C++中计算程序运行时间

    转自: C/C++中计算程序运行时间


    以前经常听人提起如何计算程序运行时间,给出一系列函数,当时没有注意,随便选了clock()最简单的方式进行计算。等到真正需要检测程序性能提升了多少,才发现这里面有很多要注意的地方。

     
    最常用的的方式:
    #include
    time_t start = clock();
    time_t end = clock();
    printf("the running time is : %f ", double(end -begin)/CLOCKS_PER_SEC);
    clock()计算的是CPU执行耗时,注意是CPU!如果有多个核并行,最后的结果是每个CPU上运算时间的总和!想要精确到毫秒,可以double(end -begin)*1000/CLOCKS_PER_SEC
     
    一般来说,只要求精确到秒的话,time是很好使的
    1. #include <</span>stdio.h>
    2. #include <</span>time.h>
    3.  
    4. int main(){
    5.     time_t t_start, t_end;
    6.     t_start = time(NULL) ;
    7.     sleep(3000);
    8.     t_end = time(NULL) ;
    9.     printf("time: %.0f s ", difftime(t_end,t_start)) ;
    10.     return 0;
    11. }
     

    如果要让程序休眠3秒,Windows使用Sleep(3000),Linux使用sleep(3),即Windows的Sleep接口的参数的单位是毫秒,Linux的sleep接口的参数的单位是秒。

    如果需要精确到毫秒,以上程序就发挥不了作用,如果在Java要达到这要求就很简单了,代码如下所示:

    下载:  Time.java
    1. public class Time {
    2.     public static void main(String[] args) {
    3.         try {
    4.             long startTime = System.currentTimeMillis();
    5.             Thread.sleep(3000);
    6.             long endTime = System.currentTimeMillis();
    7.             System.out.println("time: " + (endTime - startTime) + " ms");
    8.         } catch (InterruptedException e) {
    9.             e.printStackTrace();
    10.         }
    11.     }
    12. }

    通过Google找了一些资料后,发现C语言里没有标准的接口可以获得精确到毫秒的时间,都会调用到与操作系统相关的API,下面会分别介绍在Linux和Windows系统下的多种实现方法,希望对大家有帮助。

    Linux系统

    使用gettimeofday接口:

    下载:  gettimeofday.c
    1. #include <</span>stdio.h>
    2. #include <</span>sys/time.h>
    3.  
    4. int main() {
    5.     struct timeval start, end;
    6.     gettimeofday( &start, NULL );
    7.     sleep(3);
    8.     gettimeofday( &end, NULL );
    9.     int timeuse = 1000000 * ( end.tv_sec - start.tv_sec ) + end.tv_usec -start.tv_usec;
    10.     printf("time: %d us ", timeuse);
    11.     return 0;
    12. }

    gettimeofday能得到微秒数,比毫秒还要更精确。

    使用ftime接口:

    下载:  ftime.c
    1. #include <</span>stdio.h>
    2. #include <</span>sys/timeb.h>
    3.  
    4. long long getSystemTime() {
    5.     struct timeb t;
    6.     ftime(&t);
    7.     return 1000 * t.time + t.millitm;
    8. }
    9.  
    10. int main() {
    11.     long long start=getSystemTime();
    12.     sleep(3);
    13.     long long end=getSystemTime();
    14.  
    15.     printf("time: %lld ms ", end-start);
    16.     return 0;
    17. }

    Windows系统

    使用GetTickCount接口:

    下载:  GetTickCount.c
    1. #include <</span>windows.h>
    2. #include <</span>stdio.h>
    3.  
    4. int main() {
    5.     DWORD start, stop;
    6.     start = GetTickCount();
    7.     Sleep(3000);
    8.     stop = GetTickCount();
    9.     printf("time: %lld ms ", stop - start);
    10.     return 0;
    11. }

    Windows系统下有些编译器使用printf输出64位整数参数要使用%I64d,比如VC。

    使用QueryPerformanceX接口:

    1. #include <</span>windows.h>
    2. #include <</span>stdio.h>
    3.  
    4. int main(){
    5.     LARGE_INTEGER li;
    6.     LONGLONG start, end, freq;
    7.     QueryPerformanceFrequency(&li);
    8.     freq = li.QuadPart;
    9.     QueryPerformanceCounter(&li);
    10.     start = li.QuadPart;
    11.     Sleep(3000);
    12.     QueryPerformanceCounter(&li);
    13.     end = li.QuadPart;
    14.     int useTime =(int)((end - start) * 1000 / freq);
    15.     printf("time: %d ms ", useTime);
    16.     return 0;
    17. }

    使用GetSystemTime接口:

    下载:  GetSystemTime.c
    1. #include <</span>windows.h>
    2. #include <</span>stdio.h>
    3.  
    4. int main(){
    5.     SYSTEMTIME currentTime;
    6.     GetSystemTime(&currentTime);
    7.     printf("time: %u/%u/%u %u:%u:%u:%u %d ",           
    8.      currentTime.wYear,currentTime.wMonth,currentTime.wDay,
    9.      currentTime.wHour,currentTime.wMinute,currentTime.wSecond,
    10.      currentTime.wMilliseconds,currentTime.wDayOfWeek);
    11.     return 0;
    12. }

    这种方法没给出计算时间差的实现,只给出如何用GetSystemTime调用得到当前时间,计算时间差比较简单,根据年、月、日、时、分秒和毫秒计算出一个整数,再将两整数相减即可。


    附上我写的一个精确到微秒(us)的类:
    #include <sstream>
    #include <sys/time.h>
    
    
    // use eg: 
    //  auto _ =IntervalTimer("Interval of compute:");
    class IntervalTimer {
    public:
        IntervalTimer(std::string s): text_(s) {
            us_beg_ = get_us();
        }
        ~IntervalTimer() {
            long us_end = get_us();
            std::stringstream ss;
            ss << text_ << " " << us_end - us_beg_ << " us.";
            std::cout << ss.str() << std::endl; 
        }
    
    protected:
        long get_us() {
            struct  timeval tv;
            gettimeofday(&tv, 0x0);
            return tv.tv_usec + tv.tv_sec*1000000;
        }
    
    private:
        long us_beg_;
        std::string text_;
    };
  • 相关阅读:
    86. Partition List
    2. Add Two Numbers
    55. Jump Game
    70. Climbing Stairs
    53. Maximum Subarray
    64. Minimum Path Sum
    122. Best Time to Buy and Sell Stock II
    以场景为中心的产品设计方法
    那些产品经理犯过最大的错
    Axure教程:如何使用动态面板?动态面板功能详解
  • 原文地址:https://www.cnblogs.com/xiaouisme/p/14132616.html
Copyright © 2011-2022 走看看