Home:ALL Converter>C++ Cross-Platform High-Resolution Timer

C++ Cross-Platform High-Resolution Timer

Ask Time:2009-09-28T23:27:17         Author:Amish Programmer

Json Formatter

I'm looking to implement a simple timer mechanism in C++. The code should work in Windows and Linux. The resolution should be as precise as possible (at least millisecond accuracy). This will be used to simply track the passage of time, not to implement any kind of event-driven design. What is the best tool to accomplish this?

Author:Amish Programmer,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/1487695/c-cross-platform-high-resolution-timer
Dan :

The ACE library has portable high resolution timers also.\n\nDoxygen for high res timer:\nhttp://www.dre.vanderbilt.edu/Doxygen/5.7.2/html/ace/a00244.html",
Dirk Eddelbuettel :

I have seen this implemented a few times as closed-source in-house solutions .... which all resorted to #ifdef solutions around native Windows hi-res timers on the one hand and Linux kernel timers using struct timeval (see man timeradd) on the other hand.\n\nYou can abstract this and a few Open Source projects have done it -- the last one I looked at was the CoinOR class CoinTimer but there are surely more of them.",
Maciek :

I highly recommend boost::posix_time library for that. It supports timers in various resolutions down to microseconds I believe",
metamorphosis :

SDL2 has an excellent cross-platform high-resolution timer. If however you need sub-millisecond accuracy, I wrote a very small cross-platform timer library here.\nIt is compatible with both C++03 and C++11/higher versions of C++.",
Dan Bechard :

I found this which looks promising, and is extremely straightforward, not sure if there are any drawbacks:\n\nhttps://gist.github.com/ForeverZer0/0a4f80fc02b96e19380ebb7a3debbee5\n\n/* ----------------------------------------------------------------------- */\n/*\nEasy embeddable cross-platform high resolution timer function. For each \nplatform we select the high resolution timer. You can call the 'ns()' \nfunction in your file after embedding this. \n*/\n#include <stdint.h>\n#if defined(__linux)\n# define HAVE_POSIX_TIMER\n# include <time.h>\n# ifdef CLOCK_MONOTONIC\n# define CLOCKID CLOCK_MONOTONIC\n# else\n# define CLOCKID CLOCK_REALTIME\n# endif\n#elif defined(__APPLE__)\n# define HAVE_MACH_TIMER\n# include <mach/mach_time.h>\n#elif defined(_WIN32)\n# define WIN32_LEAN_AND_MEAN\n# include <windows.h>\n#endif\nstatic uint64_t ns() {\nstatic uint64_t is_init = 0;\n#if defined(__APPLE__)\n static mach_timebase_info_data_t info;\n if (0 == is_init) {\n mach_timebase_info(&info);\n is_init = 1;\n }\n uint64_t now;\n now = mach_absolute_time();\n now *= info.numer;\n now /= info.denom;\n return now;\n#elif defined(__linux)\n static struct timespec linux_rate;\n if (0 == is_init) {\n clock_getres(CLOCKID, &linux_rate);\n is_init = 1;\n }\n uint64_t now;\n struct timespec spec;\n clock_gettime(CLOCKID, &spec);\n now = spec.tv_sec * 1.0e9 + spec.tv_nsec;\n return now;\n#elif defined(_WIN32)\n static LARGE_INTEGER win_frequency;\n if (0 == is_init) {\n QueryPerformanceFrequency(&win_frequency);\n is_init = 1;\n }\n LARGE_INTEGER now;\n QueryPerformanceCounter(&now);\n return (uint64_t) ((1e9 * now.QuadPart) / win_frequency.QuadPart);\n#endif\n}\n/* ----------------------------------------------------------------------- */-------------------------------- */\n",
jmucchiello :

The first answer to C++ library questions is generally BOOST: http://www.boost.org/doc/libs/1_40_0/libs/timer/timer.htm. Does this do what you want? Probably not but it's a start.\n\nThe problem is you want portable and timer functions are not universal in OSes.",
Howard Hinnant :

Updated answer for an old question:\n\nIn C++11 you can portably get to the highest resolution timer with:\n\n#include <iostream>\n#include <chrono>\n#include \"chrono_io\"\n\nint main()\n{\n typedef std::chrono::high_resolution_clock Clock;\n auto t1 = Clock::now();\n auto t2 = Clock::now();\n std::cout << t2-t1 << '\\n';\n}\n\n\nExample output:\n\n74 nanoseconds\n\n\n\"chrono_io\" is an extension to ease I/O issues with these new types and is freely available here.\n\nThere is also an implementation of <chrono> available in boost (might still be on tip-of-trunk, not sure it has been released).\n\nUpdate\n\nThis is in response to Ben's comment below that subsequent calls to std::chrono::high_resolution_clock take several milliseconds in VS11. Below is a <chrono>-compatible workaround. However it only works on Intel hardware, you need to dip into inline assembly (syntax to do that varies with compiler), and you have to hardwire the machine's clock speed into the clock:\n\n#include <chrono>\n\nstruct clock\n{\n typedef unsigned long long rep;\n typedef std::ratio<1, 2800000000> period; // My machine is 2.8 GHz\n typedef std::chrono::duration<rep, period> duration;\n typedef std::chrono::time_point<clock> time_point;\n static const bool is_steady = true;\n\n static time_point now() noexcept\n {\n unsigned lo, hi;\n asm volatile(\"rdtsc\" : \"=a\" (lo), \"=d\" (hi));\n return time_point(duration(static_cast<rep>(hi) << 32 | lo));\n }\n\nprivate:\n\n static\n unsigned\n get_clock_speed()\n {\n int mib[] = {CTL_HW, HW_CPU_FREQ};\n const std::size_t namelen = sizeof(mib)/sizeof(mib[0]);\n unsigned freq;\n size_t freq_len = sizeof(freq);\n if (sysctl(mib, namelen, &freq, &freq_len, nullptr, 0) != 0)\n return 0;\n return freq;\n }\n\n static\n bool\n check_invariants()\n {\n static_assert(1 == period::num, \"period must be 1/freq\");\n assert(get_clock_speed() == period::den);\n static_assert(std::is_same<rep, duration::rep>::value,\n \"rep and duration::rep must be the same type\");\n static_assert(std::is_same<period, duration::period>::value,\n \"period and duration::period must be the same type\");\n static_assert(std::is_same<duration, time_point::duration>::value,\n \"duration and time_point::duration must be the same type\");\n return true;\n }\n\n static const bool invariants;\n};\n\nconst bool clock::invariants = clock::check_invariants();\n\n\nSo it isn't portable. But if you want to experiment with a high resolution clock on your own intel hardware, it doesn't get finer than this. Though be forewarned, today's clock speeds can dynamically change (they aren't really a compile-time constant). And with a multiprocessor machine you can even get time stamps from different processors. But still, experiments on my hardware work fairly well. If you're stuck with millisecond resolution, this could be a workaround.\n\nThis clock has a duration in terms of your cpu's clock speed (as you reported it). I.e. for me this clock ticks once every 1/2,800,000,000 of a second. If you want to, you can convert this to nanoseconds (for example) with:\n\nusing std::chrono::nanoseconds;\nusing std::chrono::duration_cast;\nauto t0 = clock::now();\nauto t1 = clock::now();\nnanoseconds ns = duration_cast<nanoseconds>(t1-t0);\n\n\nThe conversion will truncate fractions of a cpu cycle to form the nanosecond. Other rounding modes are possible, but that's a different topic.\n\nFor me this will return a duration as low as 18 clock ticks, which truncates to 6 nanoseconds.\n\nI've added some \"invariant checking\" to the above clock, the most important of which is checking that the clock::period is correct for the machine. Again, this is not portable code, but if you're using this clock, you've already committed to that. The private get_clock_speed() function shown here gets the maximum cpu frequency on OS X, and that should be the same number as the constant denominator of clock::period.\n\nAdding this will save you a little debugging time when you port this code to your new machine and forget to update the clock::period to the speed of your new machine. All of the checking is done either at compile-time or at program startup time. So it won't impact the performance of clock::now() in the least.",
JamieH :

STLSoft have a Performance Library, which includes a set of timer classes, some that work for both UNIX and Windows.",
Josh Kelley :

For C++03:\n\nBoost.Timer might work, but it depends on the C function clock and so may not have good enough resolution for you.\n\nBoost.Date_Time includes a ptime class that's been recommended on Stack Overflow before. See its docs on microsec_clock::local_time and microsec_clock::universal_time, but note its caveat that \"Win32 systems often do not achieve microsecond resolution via this API.\"\n\nSTLsoft provides, among other things, thin cross-platform (Windows and Linux/Unix) C++ wrappers around OS-specific APIs. Its performance library has several classes that would do what you need. (To make it cross platform, pick a class like performance_counter that exists in both the winstl and unixstl namespaces, then use whichever namespace matches your platform.)\n\nFor C++11 and above:\n\nThe std::chrono library has this functionality built in. See this answer by @HowardHinnant for details.",
Satbir :

I am not sure about your requirement, If you want to calculate time interval please see thread below \n\nCalculating elapsed time in a C program in milliseconds",
dcw :

Matthew Wilson's STLSoft libraries provide several timer types, with congruent interfaces so you can plug-and-play. Amongst the offerings are timers that are low-cost but low-resolution, and ones that are high-resolution but have high-cost. There are also ones for measuring pre-thread times and for measuring per-process times, as well as all that measure elapsed times.\n\nThere's an exhaustive article covering it in Dr. Dobb's from some years ago, although it only covers the Windows ones, those defined in the WinSTL sub-project. STLSoft also provides for UNIX timers in the UNIXSTL sub-project, and you can use the \"PlatformSTL\" one, which includes the UNIX or Windows one as appropriate, as in:\n\n#include <platformstl/performance/performance_counter.hpp>\n#include <iostream>\n\nint main()\n{\n platformstl::performance_counter c;\n\n c.start();\n for(int i = 0; i < 1000000000; ++i);\n c.stop();\n\n std::cout << \"time (s): \" << c.get_seconds() << std::endl;\n std::cout << \"time (ms): \" << c.get_milliseconds() << std::endl;\n std::cout << \"time (us): \" << c.get_microseconds() << std::endl;\n}\n\n\nHTH",
Patrick :

Late to the party here, but I'm working in a legacy codebase that can't be upgraded to c++11 yet. Nobody on our team is very skilled in c++, so adding a library like STL is proving difficult (on top of potential concerns others have raised about deployment issues). I really needed an extremely simple cross platform timer that could live by itself without anything beyond bare-bones standard system libraries. Here's what I found:\n\nhttp://www.songho.ca/misc/timer/timer.html\n\nReposting the entire source here just so it doesn't get lost if the site ever dies:\n\n //////////////////////////////////////////////////////////////////////////////\n// Timer.cpp\n// =========\n// High Resolution Timer.\n// This timer is able to measure the elapsed time with 1 micro-second accuracy\n// in both Windows, Linux and Unix system \n//\n// AUTHOR: Song Ho Ahn ([email protected]) - http://www.songho.ca/misc/timer/timer.html\n// CREATED: 2003-01-13\n// UPDATED: 2017-03-30\n//\n// Copyright (c) 2003 Song Ho Ahn\n//////////////////////////////////////////////////////////////////////////////\n\n#include \"Timer.h\"\n#include <stdlib.h>\n\n///////////////////////////////////////////////////////////////////////////////\n// constructor\n///////////////////////////////////////////////////////////////////////////////\nTimer::Timer()\n{\n#if defined(WIN32) || defined(_WIN32)\n QueryPerformanceFrequency(&frequency);\n startCount.QuadPart = 0;\n endCount.QuadPart = 0;\n#else\n startCount.tv_sec = startCount.tv_usec = 0;\n endCount.tv_sec = endCount.tv_usec = 0;\n#endif\n\n stopped = 0;\n startTimeInMicroSec = 0;\n endTimeInMicroSec = 0;\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// distructor\n///////////////////////////////////////////////////////////////////////////////\nTimer::~Timer()\n{\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// start timer.\n// startCount will be set at this point.\n///////////////////////////////////////////////////////////////////////////////\nvoid Timer::start()\n{\n stopped = 0; // reset stop flag\n#if defined(WIN32) || defined(_WIN32)\n QueryPerformanceCounter(&startCount);\n#else\n gettimeofday(&startCount, NULL);\n#endif\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// stop the timer.\n// endCount will be set at this point.\n///////////////////////////////////////////////////////////////////////////////\nvoid Timer::stop()\n{\n stopped = 1; // set timer stopped flag\n\n#if defined(WIN32) || defined(_WIN32)\n QueryPerformanceCounter(&endCount);\n#else\n gettimeofday(&endCount, NULL);\n#endif\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// compute elapsed time in micro-second resolution.\n// other getElapsedTime will call this first, then convert to correspond resolution.\n///////////////////////////////////////////////////////////////////////////////\ndouble Timer::getElapsedTimeInMicroSec()\n{\n#if defined(WIN32) || defined(_WIN32)\n if(!stopped)\n QueryPerformanceCounter(&endCount);\n\n startTimeInMicroSec = startCount.QuadPart * (1000000.0 / frequency.QuadPart);\n endTimeInMicroSec = endCount.QuadPart * (1000000.0 / frequency.QuadPart);\n#else\n if(!stopped)\n gettimeofday(&endCount, NULL);\n\n startTimeInMicroSec = (startCount.tv_sec * 1000000.0) + startCount.tv_usec;\n endTimeInMicroSec = (endCount.tv_sec * 1000000.0) + endCount.tv_usec;\n#endif\n\n return endTimeInMicroSec - startTimeInMicroSec;\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// divide elapsedTimeInMicroSec by 1000\n///////////////////////////////////////////////////////////////////////////////\ndouble Timer::getElapsedTimeInMilliSec()\n{\n return this->getElapsedTimeInMicroSec() * 0.001;\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// divide elapsedTimeInMicroSec by 1000000\n///////////////////////////////////////////////////////////////////////////////\ndouble Timer::getElapsedTimeInSec()\n{\n return this->getElapsedTimeInMicroSec() * 0.000001;\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// same as getElapsedTimeInSec()\n///////////////////////////////////////////////////////////////////////////////\ndouble Timer::getElapsedTime()\n{\n return this->getElapsedTimeInSec();\n}\n\n\nand the header file:\n\n//////////////////////////////////////////////////////////////////////////////\n// Timer.h\n// =======\n// High Resolution Timer.\n// This timer is able to measure the elapsed time with 1 micro-second accuracy\n// in both Windows, Linux and Unix system \n//\n// AUTHOR: Song Ho Ahn ([email protected]) - http://www.songho.ca/misc/timer/timer.html\n// CREATED: 2003-01-13\n// UPDATED: 2017-03-30\n//\n// Copyright (c) 2003 Song Ho Ahn\n//////////////////////////////////////////////////////////////////////////////\n\n#ifndef TIMER_H_DEF\n#define TIMER_H_DEF\n\n#if defined(WIN32) || defined(_WIN32) // Windows system specific\n#include <windows.h>\n#else // Unix based system specific\n#include <sys/time.h>\n#endif\n\n\nclass Timer\n{\npublic:\n Timer(); // default constructor\n ~Timer(); // default destructor\n\n void start(); // start timer\n void stop(); // stop the timer\n double getElapsedTime(); // get elapsed time in second\n double getElapsedTimeInSec(); // get elapsed time in second (same as getElapsedTime)\n double getElapsedTimeInMilliSec(); // get elapsed time in milli-second\n double getElapsedTimeInMicroSec(); // get elapsed time in micro-second\n\n\nprotected:\n\n\nprivate:\n double startTimeInMicroSec; // starting time in micro-second\n double endTimeInMicroSec; // ending time in micro-second\n int stopped; // stop flag \n#if defined(WIN32) || defined(_WIN32)\n LARGE_INTEGER frequency; // ticks per second\n LARGE_INTEGER startCount; //\n LARGE_INTEGER endCount; //\n#else\n timeval startCount; //\n timeval endCount; //\n#endif\n};\n\n#endif // TIMER_H_DEF\n",
Malte Clasen :

The StlSoft open source library provides a quite good timer on both windows and linux platforms. If you want it to implement on your own, just have a look at their sources.",