2012-06-20 54 views
3

我想打印我的函数的运行时间。出于某种原因,我的计时器总是返回0.谁能告诉我为什么?函数的运行时间

double RunningTime(clock_t time1, clock_t time2) 
{ 
    double t=time1 - time2; 
    double time = (t*1000)/CLOCKS_PER_SEC; 
    return time; 
} 

int main() 
{ 
    clock_t start_time = clock(); 


    // some code..... 


    clock_t end_time = clock(); 

    std::cout << "Time elapsed: " << double(RunningTime(end_time, start_time)) << " ms"; 

    return 0; 
} 

我试图使用gettimeofday,它仍然返回0。

double get_time() 
{ 
    struct timeval t; 
    gettimeofday(&t, NULL); 
    double d = t.tv_sec + (double) t.tv_usec/100000; 
    return d; 
} 

int main() 
{ 
     double time_start = get_time(); 

     //Some code...... 

     double time_end = get_time(); 

     std::cout << time_end - time_start; 

    return 0; 
} 

使用chrono也试过,它给了我各种编译错误:

  • 错误:#ERROR这文件需要对即将到来的ISO C++标准C++ 0x的 编译器和库支持。此支持目前是
    的实验,并且必须启用-std = C++ 0x或-std = gnu ++ 0x 编译器选项。
  • 警告:'auto'会改变C++ 0x的含义;请删除它
  • 错误:ISO C++禁止“T1”的声明,没有类型的错误: “的std ::时辰”还没有被宣布
  • 错误:请求成员在“数”“(T2 - T1 )”,这是 非类型的 'INT'

    INT主() { 自动T1 =标准::计时:: high_resolution_clock ::现在();

      //Some code...... 
    
          auto t2 = std::chrono::high_resolution_clock::now(); 
    
          std::cout << "Time elapsed: " << std::chrono::duration_cast<std::chrono::milliseconds>(t2-t1).count() << " milliseconds\n"; 
    
         return 0; 
        } 
    
+1

考虑使用''如果你想要很好的分辨率。您可以轻松地为单位指定毫秒而不是计算它。 – chris

+0

在* nix系统上,尝试'gettimeofday()'获得高分辨率时间(微秒)。 – gavinb

+0

如果你没有C++ 11,你可以考虑linux上的clock_gettime(使用'CLOCK_MONOTONIC_HR'),或'gethrtime'来处理大多数其他的UNIX变体,以及'Windows上的QueryPerformanceCounter'。 – jxh

回答

3

甲计时器滴答近似等于1/CLOCKS_PER_SEC秒,这是一毫秒的分辨率。看到一个真正的(非零)号,您应该调用一个很长的时间功能,或者使用其他库具有较高的时间分辨率设施:

  • 新的C++库11X chrono(使用MSVS 2012)
  • boost::chrono(不幸的是,该库是指很多人的)
  • POSIX功能gettimeofday,它给你一个1微秒的时间分辨率
+0

gettimeofday的弱点在于它不是单调的,并且在某些事情(如'ntpd')调整系统时间。 – jxh

+0

例如,如果机器正在尝试与网络时间服务器保持同步,则为真。但在这种情况下,它可能是适合的。 – gahcep

+0

我试过使用'gettimeofday',它仍然返回0 – Jmh2013

0

经过大量的试验和错误我gettimeofday去的。这是我的代码,我终于正常工作。

double get_time() 
{ 
    struct timeval t; 
    gettimeofday(&t, NULL); 
    double d = t.tv_sec + (double) t.tv_usec/1000000; 
    return d; 
} 

int main() 
{ 
    double time_start = get_time(); 

    //Some code......... 

    double time_end = get_time(); 

    std::cout << time_end - time_start; 

    return 0; 
} 
0

我一直在使用一个最近的解决方案使用C++ 11的lambda功能,任何时间任意函数调用或一系列的动作。

#include <ctime> 
#include <iostream> 
#include <functional> 

void timeit(std::function<void()> func) { 
    std::clock_t start = std::clock(); 

    func(); 

    int ms = (std::clock() - start)/(double) (CLOCKS_PER_SEC/1000); 

    std::cout << "Finished in " << ms << "ms" << std::endl; 
} 

int main() { 
    timeit([] { 
     for (int i = 0; i < 10; ++i) { 
      std::cout << "i = " << i << std::endl; 
     } 
    }); 

    return 0; 
}