问题
This is my very first question here and I'm also a complete newbie at C++, but I'll do my best to be as specific as possible. Please tell me if I'm being to vague:
I am trying to measure the time it takes for a sorting method (merge sort) to sort a given array of integers by using chrono and duration_cast. Here is the code snippet in question:
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";
And the output I get is always "0 seconds", no matter how big I make the array it needs to sort. Even when it sorts a million integers and there is a noticeable execution time, it still gives me the same output.
I'm basically following the example given here: http://en.cppreference.com/w/cpp/chrono/duration/duration_cast
Only instead of f() I'm using my mergesort function. How can I make it measure my sorting method properly?
EDIT: I'm using minGW to compile via Powershell in Windows 10. The command looks like this:
g++ -std=c++11 .\Merge.cpp
回答1:
TL;DR: It looks like the std::chrono
implementation (libstdc++) is quite poor on Windows and you won't get anything better than seconds.
Long version:
libstdc++ typedef
s std::chrono::high_resolution_clock
to std::chrono::system_clock
. According to the implementation a call to std::chrono::system_clock::now()
will result in a call to one of the following, depending on the platform:
syscall(SYS_clock_gettime, CLOCK_REALTIME, ...)
, which is a Linux system callclock_gettime(CLOCK_REALTIME, ...)
, which is a POSIX syscall not supported by Windowsgettimeofday(...)
, which is a POSIX function not supported by Windowsstd::time()
as a fallback
Thus, std::time()
is called internally on Windows. The encoding of std::time()
is not specified; however, most systems follow the POSIX specification:
The time() function shall return the value of time in seconds since the Epoch.
Microsoft itself does the same:
Return the time as seconds elapsed since midnight, January 1, 1970, or -1 in the case of an error.
I think it is safe to say that you won't get a higher resolution with MingW's std::chrono
.
As for your problem, you have two options:
- If your program is running on Windows only you can build your own time measurement using QueryPerformanceCounter
- If you want to keep it portable use Boost.Chrono. It uses the native Windows APIs and should offer a better resolution.
来源:https://stackoverflow.com/questions/36913864/c-chronoduration-cast-always-outputs-0-seconds