C++ chrono::duration_cast 总是输出“0 秒”

C++ chrono::duration_cast always outputs "0 seconds"

这是我在这里的第一个问题,我也是 C++ 的新手,但我会尽我所能尽可能具体。如果我含糊不清,请告诉我:

我正在尝试使用 chrono 和 duration_cast 来测量排序方法(合并排序)对给定整数数组进行排序所花费的时间。这是有问题的代码片段:

    auto t1 = std::chrono::high_resolution_clock::now();
    mergesort(sortingArray, temp, 0, num - 1);
    auto t2 = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> fp_ms = t2 - t1;
    std::cout << fp_ms.count() << " seconds\n";

而且我得到的输出始终是“0 秒”,无论我将需要排序的数组制作成多大。即使它对一百万个整数进行排序并且执行时间很长,它仍然会给我相同的输出。

我基本上遵循此处给出的示例:http://en.cppreference.com/w/cpp/chrono/duration/duration_cast

只是我没有使用 f(),而是使用了我的归并排序函数。如何让它正确测量我的排序方法?

编辑:我在 Windows 10 中使用 minGW 通过 Powershell 进行编译。命令如下所示:

g++ -std=c++11 .\Merge.cpp

TL;DR:看起来 std::chrono 实现 (libstdc++) 在 Windows 上很差,你不会得到比秒。

长版:

libstdc++ typedefs std::chrono::high_resolution_clockstd::chrono::system_clock。根据 implementation 调用 std::chrono::system_clock::now() 将导致调用以下之一,具体取决于平台:

  • syscall(SYS_clock_gettime, CLOCK_REALTIME, ...),这是一个Linux系统调用
  • clock_gettime(CLOCK_REALTIME, ...),POSIX 系统调用不受 Windows
  • 支持
  • gettimeofday(...),POSIX 函数不受 Windows
  • 支持
  • std::time() 作为备用

因此,std::time() 在 Windows 上被内部调用。 std::time()的编码没有指定;但是,大多数系统遵循 POSIX specification:

The time() function shall return the value of time in seconds since the Epoch.

微软自己做 the same:

Return the time as seconds elapsed since midnight, January 1, 1970, or -1 in the case of an error.

我认为可以肯定地说 MingW 的 std::chrono 无法获得更高的分辨率。

对于您的问题,您有两种选择:

  1. 如果您的程序在 Windows 上 运行 只有您可以使用 QueryPerformanceCounter
  2. 建立您自己的时间测量
  3. 如果您想保持它的便携性,请使用 Boost.Chrono. It uses the native Windows APIs 并且应该提供更好的分辨率。