C++ 计算 代码运行时间的 几种方法 .

有许多专门的测试工具,测试的准确性很高,本文说的是一些简单的测试方法,这些方法多数是记录CPU的运行时间,没有考虑操作系统的分时复用,不过不太严格的情况都可一用。

1.  #include <time.h>
long start=clock(),end(0);
//ToDo:process code
end=clock();
long result=(end-start)/1000

2.  windows 平台
#include <windows.h>
double start=getticktime(),end(0);
//ToDo:process code
end=getticktime();
double result=end-start;

3.windows 平台
#include <windows.h>
    LARGE_INTEGER  frequency,start,end;  
    QueryPerformanceFrequency(&frequency);  
    QueryPerformanceCounter(&start);  
 //ToDO:process code
    QueryPerformanceCounter(&end);  
    double   d   =   (double)(end.QuadPart   -   start.QuadPart)   /   (double)frequency.QuadPart   *   1000.0;

4.根据线程而来的
CThreadTime   ElapsedTime;  
  ElapsedTime.BeginGetElapsedTime();  
   
  //TODO:   Your   performance   code  
   
  int   nThreadTine   =   ElapsedTime.EndGetElapsedTime();  
   
   
  该类的实现如下:  
  //   This   class   is   for   getting   the   elapsed   thread   time   of   the   CPU,   the   unit   is   ms  
  //   the   usage   is:    
  //    
  //   CThreadTime   ElapsedTime;  
  //   ElapsedTime.BeginGetElapsedTime();  
  //   TODO:   Your   performance   code  
  //   int   nThreadTine   =   ElapsedTime.EndGetElapsedTime();  
  //  
   
   
  #include   <Windows.h>  
   
  class   CThreadTime  
  {  
  public:          
          void         BeginGetElapsedTime();  
          __int64   EndGetElapsedTime();  
   
  private:  
          __int64   FileTimeToQuadWord(PFILETIME   pft);  
   
  private:  
          FILETIME   ftKernelTimeStart;  
          FILETIME   ftKernelTimeEnd;  
          FILETIME   ftUserTimeStart;  
          FILETIME   ftUserTimeEnd;  
          FILETIME   ftDummy;  
  };  
   
  //   Get   the   time   elapsed   since   the   thread   start  
  inline   void   CThreadTime::BeginGetElapsedTime()  
  {  
          GetThreadTimes(GetCurrentThread(),   &ftDummy,   &ftDummy,   &ftKernelTimeStart,   &ftUserTimeStart);  
  }  
   
  //   Calculate   the   time   elapsed    
  inline   __int64   CThreadTime::EndGetElapsedTime()  
  {  
          GetThreadTimes(GetCurrentThread(),   &ftDummy,   &ftDummy,   &ftKernelTimeEnd,   &ftUserTimeEnd);  
   
          __int64   qwKernelTimeElapsed   =   FileTimeToQuadWord(&ftKernelTimeEnd)   -   FileTimeToQuadWord(&ftKernelTimeStart);  
          __int64   qwUserTimeElapsed   =   FileTimeToQuadWord(&ftUserTimeEnd)   -   FileTimeToQuadWord(&ftUserTimeStart);  
   
          //   Get   total   time   duration   by   adding   the   kernel   and   user   times.  
          //   the   default   is   100ns,   so   we   convert   it   to   ms  
          return   (qwKernelTimeElapsed   +   qwUserTimeElapsed)   /   10000;  
  }   
   
inline   __int64   CThreadTime::FileTimeToQuadWord(PFILETIME   pft)    
  {  
          return   (Int64ShllMod32(pft->dwHighDateTime,   32)   |   pft->dwLowDateTime);  
  }

 

帖个算法给你:

// This class is for getting the elapsed thread time of the CPU, the unit is ms
// the usage is: 
// 
// CThreadTime ElapsedTime;
// ElapsedTime.BeginGetElapsedTime();
// TODO: Your performance code
// int nThreadTine = ElapsedTime.EndGetElapsedTime();
//


#include <Windows.h>

class CThreadTime
{
public:    
    void    BeginGetElapsedTime();
    __int64 EndGetElapsedTime();

private:
    __int64 FileTimeToQuadWord(PFILETIME pft);

private:
    FILETIME ftKernelTimeStart;
    FILETIME ftKernelTimeEnd;
    FILETIME ftUserTimeStart;
    FILETIME ftUserTimeEnd;
    FILETIME ftDummy;
};

// Get the time elapsed since the thread start
inline void CThreadTime::BeginGetElapsedTime()
{
    GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeStart, &ftUserTimeStart);
}

// Calculate the time elapsed 
inline __int64 CThreadTime::EndGetElapsedTime()
{
    GetThreadTimes(GetCurrentThread(), &ftDummy, &ftDummy, &ftKernelTimeEnd, &ftUserTimeEnd);

    __int64 qwKernelTimeElapsed = FileTimeToQuadWord(&ftKernelTimeEnd) - FileTimeToQuadWord(&ftKernelTimeStart);
    __int64 qwUserTimeElapsed = FileTimeToQuadWord(&ftUserTimeEnd) - FileTimeToQuadWord(&ftUserTimeStart);

    // Get total time duration by adding the kernel and user times.
    // the default is 100ns, so we convert it to ms
    return (qwKernelTimeElapsed + qwUserTimeElapsed) / 10000;
}

inline __int64 CThreadTime::FileTimeToQuadWord(PFILETIME pft) 
{
    return (Int64ShllMod32(pft->dwHighDateTime, 32) | pft->dwLowDateTime);
}

最后出来的是毫秒精度,当然也可以有更高精度,只要在那个10000上做文章就ok了。

/

 

Unix™ Systems Programming: Communication, Concurrency, and Threads

9.1.5 Contrasting elapsed time to processor time

#include <sys/times.h>

  clock_t times(struct tms *buffer);

The struct tms structure contains at least the following members.

clock_t  tms_utime;   /* user CPU time of process */
clock_t  tms_stime;   /* system CPU time on behalf of process */
clock_t  tms_cutime   /* user CPU time of process and terminated children */
clock_t  tms_cstime;  /* system CPU time of process and terminated children */




程序Program 9.4 cpufraction.c及Program 9.5 timechild.c
分别说明了如何计算程序中某个函数的CPU时间和子程序的执行时间。
这2个例子或许对你有帮助。

9.3、9.5节的内容也可参考,算是另外2种解决方法。

Program 9.4 cpufraction.c

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <sys/times.h>

  5. void function_to_time(void);

  6. int main(void) {
  7.    double clockticks, cticks;
  8.    clock_t tcend, tcstart;
  9.    struct tms tmend, tmstart;

  10.    if ((clockticks = (double) sysconf(_SC_CLK_TCK)) == -1) {
  11.       perror("Failed to determine clock ticks per second");
  12.       return 1;
  13.    }
  14.    printf("The number of ticks per second is %f\n", clockticks);
  15.    if (clockticks == 0) {
  16.       fprintf(stderr, "The number of ticks per second is invalid\n");
  17.       return 1;
  18.    }
  19.    if ((tcstart = times(&tmstart)) == -1) {
  20.       perror("Failed to get start time");
  21.       return 1;
  22.    }
  23.    function_to_time();
  24.    if ((tcend = times(&tmend)) == -1) {
  25.       perror("Failed to get end times");
  26.       return 1;

  27.    }
  28.    cticks = tmend.tms_utime + tmend.tms_stime
  29.              - tmstart.tms_utime - tmstart.tms_stime;
  30.    printf("Total CPU time for operation is %f seconds\n",cticks/clockticks);
  31.    if ((tcend <= tcstart) || (tcend < 0) || (tcstart < 0)) {
  32.       fprintf(stderr, "Tick time wrapped, couldn't calculate fraction\n);
  33.       return 1;
  34.    }
  35.    printf("Fraction of CPU time used is %f\n", cticks/(tcend - tcstart));
  36.    return 0;
  37. }
复制代码



Program 9.5 timechild.c

  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <sys/times.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. #include "restart.h"

  8. int main(int argc, char *argv[]) {
  9.    pid_t child;
  10.    double clockticks;
  11.    double cticks;
  12.    struct tms tmend;

  13.    if (argc < 2){   /* check for valid number of command-line arguments */
  14.       fprintf (stderr, "Usage: %s command\n", argv[0]);
  15.       return 1;
  16.    }
  17.    if ((child = fork()) == -1) {
  18.       perror("Failed to fork");
  19.       return 1;
  20.    }
  21.    if (child == 0) {                                 /* child code */
  22.       execvp(argv[1], &argv[1]);
  23.       perror("Child failed to execvp the command");
  24.       return 1;
  25.    }
  26.    if (r_wait(NULL) == -1) {                         /* parent code */
  27.       perror("Failed to wait for child");
  28.       return 1;
  29.    }
  30.    if (times(&tmend) == (clock_t)-1) {
  31.       perror("Failed to get end time");
  32.       return 1;
  33.    }
  34.    if ((clockticks = (double) sysconf(_SC_CLK_TCK)) == -1) {
  35.        perror("Failed to determine clock ticks per second");
  36.        return 1;
  37.    }
  38.    if (clockticks == 0) {
  39.       fprintf(stderr, "Invalid number of ticks per second\n");
  40.       return 1;
  41.    }
  42.    cticks = tmend.tms_cutime + tmend.tms_cstime
  43.            - tmend.tms_utime - tmend.tms_stime;
  44.    printf("%s used %ld clock ticks or %f seconds\n", argv[1],
  45.           (long)cticks, cticks/clockticks);
  46.    return 0;
  47. }
复制代码


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值