29

I am using boost 1.46 which does not include boost::timer, What other way can I time my functions.

I am currently doing this:

time_t now = time(0);
<some stuff>
time_t after = time(0);

cout << after - now << endl; 

but it just gives the answer in seconds, so if the function takes < 1s it displays 0.

Thanks

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Aly
  • 15,865
  • 47
  • 119
  • 191

5 Answers5

31

In linux or Windows:

#include <ctime>
#include <iostream>

int
main(int, const char**)
{
     std::clock_t    start;

     start = std::clock();
     // your test
     std::cout << "Time: " << (std::clock() - start) / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl;
     return 0;
}

Good Luck ;)

marsh
  • 2,592
  • 5
  • 29
  • 53
Quentin Perez
  • 2,833
  • 20
  • 22
  • 23
    Be aware that this measures CPU time, not elapsed time. E.g. if the function sleeps this will not be measured. – Étienne Jun 18 '14 at 09:54
  • 2
    That's CPU time, there will be problems when sleep or multithreading – Fei Jiang Sep 20 '14 at 13:14
  • If you *do* want CPU time, you should use `clock_gettime` and specify whether you want process time or thread time, or use `getrusage` and specify if you want to include children. – o11c May 07 '16 at 17:55
28

Using std::chrono:

#include <chrono>
#include <thread>
#include <iostream>

// There are other clocks, but this is usually the one you want.
// It corresponds to CLOCK_MONOTONIC at the syscall level.
using Clock = std::chrono::steady_clock;
using std::chrono::time_point;
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using namespace std::literals::chrono_literals;
using std::this_thread::sleep_for;

int main()
{
    time_point<Clock> start = Clock::now();
    sleep_for(500ms);
    time_point<Clock> end = Clock::now();
    milliseconds diff = duration_cast<milliseconds>(end - start);
    std::cout << diff.count() << "ms" << std::endl;
}

std::chrono is C++11, std::literals is C++14 (otherwise you need milliseconds(500)).

o11c
  • 15,265
  • 4
  • 50
  • 75
  • This is helpful, thanks. I used `high_resolution_clock` instead of `Clock` and `nanoseconds` instead of `milliseconds`, for timing some critical-section function calls that take only a few hundred nanoseconds each. – theferrit32 Feb 07 '20 at 22:45
  • @theferrit32 `high_resolution_clock` is flat-out **wrong** since it's not guaranteed to be steady; on Linux it is an alias for`system_clock`. But `steady_clock` also has nanosecond resolution, I just did the `duration_cast` to something arbitrary for printing purposes. – o11c Feb 07 '20 at 23:22
9

Turns out there is a version of time in boost 1.46 (just in different location). Thanks to @jogojapan for pointing it out.

It can be done like this:

#include <boost/timer.hpp>

timer t;
<some stuff>
std::cout << t.elapsed() << std::endl;

Or alternatively using std libs as @Quentin Perez has pointed out (and I will accept as is what was originally asked)

Aly
  • 15,865
  • 47
  • 119
  • 191
3

Building on Quentin Perez's solution, you can pass an arbitrary function to time using std::function and a lambda.

#include <ctime>
#include <iostream>
#include <functional>

void timeit(std::function<void()> func) {
    std::clock_t start = std::clock();

    func();

    int ms = (std::clock() - start) / (double) (CLOCKS_PER_SEC / 1000);

    std::cout << "Finished in " << ms << "ms" << std::endl;
}

int main() {
    timeit([] {
        for (int i = 0; i < 10; ++i) {
            std::cout << "i = " << i << std::endl;
        } 
    });

    return 0;
}
2

You can use a long to hold the current time value as a start value, and then convert the current time to a double. here is some snippet code to use as an example.

#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <sys/timeb.h>
int main()
{

struct      _timeb tStruct;
double      thisTime;
bool        done = false;
long        startTime;

 struct _timeb
 {
 int   dstflag;   // holds a non-zero value if daylight saving time is in effect
 long  millitm;   // time in milliseconds since the last one-second hack
 long  time;      // time in seconds since 00:00:00 1/1/1970
 long  timezone;  // difference in minutes moving west from UTC

 };

  _ftime(&tStruct); // Get start time

thisTime = tStruct.time + (((double)(tStruct.millitm)) / 1000.0); // Convert to double
startTime = thisTime;                                             // Set the starting time (when the function begins)


while(!done)     // Start an eternal loop
    {
    system("cls");  // Clear the screen
    _ftime(&tStruct);    // Get the current time
    thisTime = tStruct.time + (((double)(tStruct.millitm)) / 1000.0); // Convert to double
    // Check for 5 second interval to print status to screen
    cout << thisTime-startTime; // Print it. 

    }
}
prototypik
  • 2,726
  • 1
  • 18
  • 21