CLOCKS_PER_SEC是否意味着每台计算机都有不同的时间概念?

问题描述 投票:1回答:1

我们正在运行一些基准测试,我们注意到function foo调用function bar并等待响应所花费的时间比function bar少。 Foo驻留在客户端上,客户端是一个单独的物理机器,并且它位于服务器上,该服务器是一台独立的机器,并且通过TCP服务器进行通信。我们正在使用<ctime>,我们正在调用clock()

/*
* resides on client machine
*/
foo ()
{
    clock_t start,stop;
    start = clock();
    /*
     * Blocking TCP call to bar() on server
     * Uses callback functions
    */
    stop = clock();
    std::cout<<stop-start;
}
/*
 * Function on server which executes some could and returns
 * it's run time to the client machine
 */
bar ()
{
    clock_t start,stop;
    start = clock();
    /*connect to international space station and back*/
    stop = clock();
    std::cout<<stop-start;
}
foo();
bar();
foo() - bar();

我们得到的输出是类似的

100000
200000
-100000

我们怀疑问题是一个CPU的时间感比另一个CPU快,并导致这种不匹配。获得有意义的时间指标的最佳方法是什么(即基于人的时间,而不是抽象的CPU速度)。

c++ time
1个回答
1
投票

你很可能将苹果与橙子进行比较。无法保证您的两台机器对clock()使用相同的分辨率。也许更有用的是确保你的时间数字是一致的单位,比如秒。

std::cout << (stop-start)/CLOCKS_PER_SEC;

或者,您可能想尝试使用Modern C ++和<chrono>

using std::chrono;
auto start = high_resolution_clock::now();
...
auto stop = high_resolution_clock::now();
std::cout << duration_cast< duration<float> >(stop-start).count()
          << " seconds" << std::endl;

(虽然值得注意的是high_resolution_clock可能被实现为system_clock; steady_clock专门用于计时,例如你正在尝试。也可能有非便携式解决方案具有更高的分辨率,这些解决方案是硬件/操作系统特定的。)

© www.soinside.com 2019 - 2024. All rights reserved.