Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time in milliseconds to profile a function duration

Tags:

c++

profiling

I have a function that writes a file. I need to profile the function in with two parameters, so I can see the difference. (Do not tell me about Visual Studios Profiling tools, I want to do it by myself). I want to apply something like this:

double start = getTime();
myFunction("param1");
double request = getTime() - start;
printf_s("Request time: %f", request);

How can I do this? (what have above is just pseudo-code, I don't know the real functions names)

like image 357
Victor Avatar asked Aug 03 '13 08:08

Victor


2 Answers

Use std::chrono, here is an example that will work for your code:

#include <chrono>
int main()
{
    using milli = std::chrono::milliseconds;
    auto start = std::chrono::high_resolution_clock::now();
    myFunction("param1");
    auto finish = std::chrono::high_resolution_clock::now();
    std::cout << "myFunction() took "
              << std::chrono::duration_cast<milli>(finish - start).count()
              << " milliseconds\n";
}
like image 117
Andreas DM Avatar answered Nov 15 '22 04:11

Andreas DM


You can use either:

  1. a std::clock variable and divide it by CLOCKS_PER_SEC in order to obtain the seconds (needs #include <ctime>)
  2. for WinAPI you can use GetTickCount() and divide it by 1000 in order to obtain the seconds.
like image 27
Iosif Murariu Avatar answered Nov 15 '22 04:11

Iosif Murariu