Csi
Csi

Reputation: 526

Calculate time to execute a function

I need to calculate the execution time of a function.

Currently, I use time.h

At the beginning of the function:

time_t tbegin,tend;
double texec=0.000;
time(&tbegin);

Before the return:

 time(&tend);
 texec = difftime(tend,tbegin);

It works fine but give me a result in texec as a integer.

How can I have my execution time in milliseconds ?

Upvotes: 2

Views: 8743

Answers (4)

udit043
udit043

Reputation: 1620

Most of the simple programs have computation time in milliseconds. So, I suppose, you will find this useful.

#include <time.h>
#include <stdio.h>

int main() {
    clock_t start = clock();
    // Executable code
    clock_t stop = clock();

    double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
    printf("Time elapsed in ms: %f\n", elapsed);
}

If you want to compute the run-time of the entire program and you are on a Unix system, run your program using the time command, like this: time ./a.out

Upvotes: 5

vsoftco
vsoftco

Reputation: 56577

You can use a lambda with auto parameters in C++14 to time your other functions. You can pass the parameters of the timed function to your lambda. I'd do it like this:

// Timing in C++14 with auto lambda parameters

#include <iostream>
#include <chrono>

// need C++14 for auto lambda parameters
auto timing = [](auto && F, auto && ... params)
{
    auto start = std::chrono::steady_clock::now();
    std::forward<decltype(F)>(F)
    (std::forward<decltype(params)>(params)...); // execute the function
    return std::chrono::duration_cast<std::chrono::milliseconds>(
               std::chrono::steady_clock::now() - start).count();
};

void f(std::size_t numsteps) // we'll measure how long this function runs
{
    // need volatile, otherwise the compiler optimizes the loop
    for (volatile std::size_t i = 0; i < numsteps; ++i);
}

int main()
{
    auto taken = timing(f, 500'000'000); // measure the time taken to run f()
    std::cout << "Took " << taken << " milliseconds" << std::endl;

    taken = timing(f, 100'000'000); // measure again
    std::cout << "Took " << taken << " milliseconds" << std::endl;
}

The advantage is that you can pass any callable object to the timing lambda.

But if you want to keep it simple, you can just do:

auto start = std::chrono::steady_clock::now();
your_function_call_here();
auto end = std::chrono::steady_clock::now();
auto taken = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << taken << " milliseconds";

If you know you're not going to change the system time during the run, you can use a std::chrono::high_resolution_clock instead, which may be more precise. std::chrono::steady_clock is however un-sensitive to system time changes during the run.

PS: In case you need to time a member function, you can do:

// time member functions
template<class Return, class Object, class... Params1, class... Params2>
auto timing(Return (Object::*fp)(Params1...), Params2... params)
{
    auto start = std::chrono::steady_clock::now();
    (Object{}.*fp)(std::forward<decltype(params)>(params)...);
    return std::chrono::duration_cast<std::chrono::milliseconds>(
               std::chrono::steady_clock::now() - start).count();
};

then use it as

// measure the time taken to run X::f()
auto taken = timing(&X::f, 500'000'000);
std::cout << "Took " << taken << " milliseconds" << std::endl;

to time e.g. X::f() member function.

Upvotes: 4

sp2danny
sp2danny

Reputation: 7687

in the header <chrono> there is a class std::chrono::high_resolution_clock
that does what you want. it's a bit involved to use though;

#include <chrono>
using namespace std;
using namespace chrono;

auto t1 = high_resolution_clock::now();
// do calculation here
auto t2 = high_resolution_clock::now();
auto diff = duration_cast<duration<double>>(t2 - t1); 
// now elapsed time, in seconds, as a double can be found in diff.count()
long ms = (long)(1000*diff.count());

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172628

You can create a function like this source:

typedef unsigned long long timestamp_t;

static timestamp_t
timestampinmilliseconf ()
{
  struct timeval now;
  gettimeofday (&now, NULL);
  return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
}

Then you can use this to get the time difference.

timestamp_t time1 = get_timestamp();
// Your function
timestamp_t time2 = get_timestamp();

For windows you can use this function:

#ifdef WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif

typedef long long int64; typedef unsigned long long uint64;

/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
 * windows and linux. */

int64 GetTimeMs64()
{
#ifdef WIN32
 /* Windows */
 FILETIME ft;
 LARGE_INTEGER li;

 /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
  * to a LARGE_INTEGER structure. */
 GetSystemTimeAsFileTime(&ft);
 li.LowPart = ft.dwLowDateTime;
 li.HighPart = ft.dwHighDateTime;

 uint64 ret = li.QuadPart;
 ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
 ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */

 return ret;
#else
 /* Linux */
 struct timeval tv;

 gettimeofday(&tv, NULL);

 uint64 ret = tv.tv_usec;
 /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
 ret /= 1000;

 /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
 ret += (tv.tv_sec * 1000);

 return ret;
#endif
}

Source

Upvotes: 2

Related Questions