Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get local time in nanoseconds [duplicate]

Tags:

Possible Duplicate:
C++ Timer function to provide time in nano seconds

I need to measure the duration of a function execution in nanoseconds resolution. Is it possible? Our ordinary computer hardware and software are able to give such a precision for time? If yes how to accomplish that with c++? Is it possible with Boost library?

like image 743
Narek Avatar asked Oct 17 '12 15:10

Narek


2 Answers

Yes, today most hardware supports this sort of resolution, and the C++ standard library has an API that can support it as well. Unfortunately not all implementations of C++ actually do provide it.

The API is the <chrono> library introduced in C++11:

#include <iostream> #include <chrono>  int main() {     auto start = std::chrono::high_resolution_clock::now();      // operation to be timed ...      auto finish = std::chrono::high_resolution_clock::now();     std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(finish-start).count() << "ns\n"; } 

The <chrono> implementation in libc++ for Darwin provides nanosecond resolution, but it seems the implementation in VS2012 only goes to tenths of milliseconds. The above code will still give times in terms of nanoseconds, but timings less than 100 microseconds will end up being zero nanoseconds.

Boost also provides an implemenation, boost::chrono, which does seem to use nanoseconds on Windows. It's also usable with C++03.

#include <boost/chrono.hpp>  int main() {     boost::chrono::high_resolution_clock::time_point t1 =         boost::chrono::high_resolution_clock::now();      boost::chrono::high_resolution_clock::time_point t2 =         boost::chrono::high_resolution_clock::now();      std::cout << boost::chrono::duration_cast<boost::chrono::nanoseconds>(t2-t1) << "\n";     // boost chrono has more advanced output, .count() isn't needed, nor is manually writing out the units } 
like image 135
bames53 Avatar answered Sep 23 '22 12:09

bames53


I'm not sure if you're looking for clock or difftime, but one of these should be what you're looking for:

http://www.cplusplus.com/reference/clibrary/ctime/clock/

http://www.cplusplus.com/reference/clibrary/ctime/difftime/

You can use this before and after functions and compare the differences of runtimes to see the overall runtime of a function.

like image 44
mttalxndrgrrtt Avatar answered Sep 23 '22 12:09

mttalxndrgrrtt