简体   繁体   中英

Measuring time in a multithreaded C++ application

I'm writing an application using C++ and OpenMP and I want to reliably (and correctly) measure time of execution of parts of it. I have reviewed a few options (Windows, TDM-GCC x64 4.8.1):

  1. omp_get_wproc and clock seem to do the job but documentation (in direct contradiction to actual behavior) says that they measure total time resources consumed by given process (that is, eg one second with two working threads counts as two seconds). The "correct" behavior is not what I want,
  2. time / difftime don't have enough resolution,
  3. GetProcessTime (WinAPI) does what clock should do and is platform-specific,
  4. QueryPerformanceCounter (WinAPI) seems to be the way to go but is platform-specific,
  5. C++11 high_resolution_clock works ok but it's a part of a new standard.

My question, primarily, is: how do people doing scientific computing do this, and why do it that way? And, is the behavior of clock a bug in my implementation of standard library or a too popular misconception?

EDIT: Small explanation: I'm a bit hesitant to use C++11 because I'll probably run my code on a cluster with somewhat old software.

Copied directly from my current research project:

#include <chrono>
#include <type_traits>

/** @brief Best available clock. */
using clock_type = typename std::conditional<
  std::chrono::high_resolution_clock::is_steady,
  std::chrono::high_resolution_clock,
  std::chrono::steady_clock>::type;

We want to measure wall time, not user-space CPU cycles to be fair and account for the multi-threading overhead as well. Unfortunately, many implementations define high_resolution_clock as an alias for real_time_clock which would spoil our results in case the system time is adjusted during our measurements.

Yes, std::chrono is a C++11 feature but if this is research as you say, what stops you from using the most modern compiler? You won't need your code to compile on the most weird platform that might exist somewhere in some dusty cellar of a customer. Anyway, if you just cannot have C++11, you can easily implement these clocks yourself. They are (at least in GNU libstdc++) just thin wrappers around clock_gettime .

You didn't mention boost::chrono . Same as C++11 chrono , but works with C++03 compiler.

Also, I cannot understand your hesitation about C++11. We are almost in 2015, and C++11 is not that new. It is even not the most recent standard. So, #include <chrono> is a way to go.

Note however, that chrono is somewhat broken in Visual Studio 2013 Standard library implementation. I, personally, use std::chrono everywhere and swap it to boost::chrono via conditional defines and typedef s. Hope they'll fix it in Visual Studio Next.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM