Question:
is it possible to count the execution time of a certain function in C++?
anonymous
2011-03-11 13:24:54 UTC
is it possible to count the execution time of a certain function in C++?
Four answers:
?
2011-03-13 09:09:48 UTC
In pure C++, it can only be done if the compiler supports the new draft C++ standard:



#include

#include

#include

#include

void slow_function()

{

     std::vector v(10000000);

     iota(v.begin(), v.end(), 1);

     std::cout << std::accumulate(v.begin(), v.end(), 0ULL) << '\n';

}

typedef std::chrono::duration> ms;

int main()

{

     auto before = std::chrono::system_clock::now();

     slow_function();

     auto now = std::chrono::system_clock::now();

     long diff = std::chrono::duration_cast(now - before).count();

     std::cout << "time: " << diff << " ms" << std::endl;

}



test run: https://ideone.com/0qTxk



In 1998 C++, this requires third-party libraries or OS-specific system calls. The most portable library is boost.date_time:



#include

#include

#include

#include

#include

namespace pt = boost::posix_time;

void slow_function()

{

     std::vector v(10000000, 1);

     partial_sum(v.begin(), v.end(), v.begin());

     std::cout << accumulate(v.begin(), v.end(), 0ULL) << '\n';

}

int main()

{

     pt::ptime before = pt::microsec_clock::local_time();

     slow_function();

     pt::ptime now = pt::microsec_clock::local_time();

     std::cout << "time: " << (now-before) << " ms" << std::endl;

}



test run: https://ideone.com/oPXrY
no1home2day
2011-03-11 13:42:13 UTC
Use C's version of the Time() function before and after the function call, then have C print out the two times, or calculate the difference between the two times and print that one out.
anonymous
2011-03-11 13:46:37 UTC
Yes



DWORD dwBefore = timeGetTime();



Code here



DWORD dwAfter = timeGetTime();

DWORD dwTotalTime = dwAfter - dwBefore;
ScottD_Arch
2011-03-12 10:34:08 UTC
In linux you want to use clock_gettime(CLOCK_MONOTONIC


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...