功能运行时间

时间:2012-06-20 00:08:51

标签: c++ time clock

我想打印我的功能的运行时间。由于某种原因,我的计时器总是返回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启用 编译器选项。
  • 警告:&#39; auto&#39;将改变C ++ 0x中的含义;请删除它
  • 错误:ISO C ++禁止声明&#39; t1&#39;没有类型错误: &#39;的std ::计时&#39;尚未宣布
  • 错误:请求会员&#39;计算&#39; in&#39;(t2-t1)&#39;,其中 非类型&#39; int&#39;

    int main()         {                 auto t1 = std :: chrono :: high_resolution_clock :: now();

                //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;
        }
    

3 个答案:

答案 0 :(得分:4)

计时器滴答约等于1 / CLOCKS_PER_SEC秒,这是毫秒级的分辨率。要查看真实(非零)数字,您应该调用一个非常长的函数或使用另一个具有更高时间分辨率的库:

  • new c ++ 11x library chrono(使用MSVS 2012)
  • boost::chrono(不幸的是,图书馆引用了很多其他人)
  • POSIX函数gettimeofday,它为您提供1微秒的时间分辨率

答案 1 :(得分: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;
}

答案 2 :(得分: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;
}
相关问题