2014-07-03 102 views
3

我正在尝试对一段代码进行基准测试。正是基于此代码here与有趣的部分基本上看起来像这样:如何在C++中获得一段代码的执行时间?

auto t0 = std::chrono::high_resolution_clock::now(); 
    ... 
    auto t1 = std::chrono::high_resolution_clock::now(); 
    std::cout << secs(t1-t0).count() << " s\n"; 

的问题是,我是一个共享的机器上,这是给我挂钟时间,所以我的成绩没有给我任何东西是一致的。我真正需要的是某种秒表工具,它可以让我得到我的代码运行的时间,而不是花时间。有什么选择?如果涉及系统特定的调用,我在Linux机器上,但如果可能的话,我宁愿保持此代码的便携性。

我看了其他问题,如thisthis,但他们似乎都提供壁挂时间解决方案。

+3

你有没有考虑在'main'隔离代码,编译,并通过['time'(http://en.wikipedia.org/wiki/Time_(Unix上运行它))? (不是测量小块代码的最佳选择,但是因为您使用的是秒数,所以我认为这应该足够好) –

+0

我可以将其作为最后一招,但我正在运行大量测试配置,如果我必须保持复制到主体,这个测试将花费更长的时间,并且会少得多愉快 – GBleaney

+0

当你说“时间”,你的意思是CPU时间?如果您要排除所有其他进程对CPU的使用,您是否想要包含I/O的时间? – wallyk

回答

4

如果在您的操作系统上可用,您可以使用times API获得与time命令中内置的类似结果。

#include <sys/times.h> 
... 
struct tms start, end; 
times(&start); 
//Do command 
times(&end); 
clock_t usr_time = end->tms_utime - start->tms_utime; 
clock_t sys_time = end->tms_stime - start->tms_stime; 

要100%完成,你应该检查的时间,结果不等于-1否则检查errno代码。

1

理想情况下,你的问题下的评论中提到,你应该隔离你正在试图衡量内部main,只是使用UNIX time命令行工具,它报告usersystem时间的一段代码。

如果您无法做到这一点,请考虑查看source codetime,并可能使用相同的技术来测试您的代码。

1

我想你需要使用clock_gettime()以下时钟CLOCK_PROCESS_CPUTIME_IDCLOCK_THREAD_CPUTIME_ID。他们提供了一个进程/线程所消耗的CPU时间。

CLOCK_PROCESS_CPUTIME_ID 
    High-resolution per-process timer from the CPU. 
CLOCK_THREAD_CPUTIME_ID 
    Thread-specific CPU-time clock. 

参考:

我认为,让merlin2011的建议是不可行的在许多情况下,因为隔离可能需要大量的工作,同时增加两条线的代码与clock_gettime()是相当实用的。你甚至可以把课程打到clock_gettime()

1

对于Linux

#include <time.h> 
    #include <stdio.h> 

    double theseSecs = 0.0; 
    double startSecs = 0.0; 
    double secs; 
    double CPUsecs = 0.0; 
    double CPUutilisation = 0.0; 
    double answer = 0; 
    clock_t starts; 

    void start_CPU_time() 
    {  
     starts = clock();; 
     return; 
    } 

    void end_CPU_time() 
    { 
     CPUsecs = (double)(clock() - starts)/(double)CLOCKS_PER_SEC; 
     return; 
    }  

    struct timespec tp1; 
    void getSecs() 
    { 
    clock_gettime(CLOCK_REALTIME, &tp1); 
    theseSecs = tp1.tv_sec + tp1.tv_nsec/1e9;   
    return; 
    } 

    void start_time() 
    { 
     getSecs(); 
     startSecs = theseSecs; 
     return; 
    } 

    void end_time() 
    { 
     getSecs(); 
     secs = theseSecs - startSecs; 
     return; 
    }  

    void calculate() 
    { 
     int i, j; 
     for (i=1; i<100001; i++) 
     { 
      for (j=1; j<10001; j++) 
      { 
       answer = answer + (float)i/100000000.0; 
      } 
     } 
    } 

void main() 
{ 
    start_time(); 
    start_CPU_time(); 
    calculate(); 
    end_time(); 
    end_CPU_time(); 
    CPUutilisation = CPUsecs/secs * 100.0; 
    printf("\n Answer %10.1f, Elapsed Time %7.4f, CPU Time %7.4f, CPU Ut %3.0f%\n", 
       answer, secs, CPUsecs, CPUutilisation); 
} 
相关问题