tags:

views:

2183

answers:

8

What's the best way to calculate a time difference in C++? I'm timing the execution speed of a program, so I'm interested in milliseconds. Better yet, seconds.milliseconds..

The accepted answer works, but needs to include ctime or time.h as noted in the comments.

Another answer (dupe) can be found here

+10  A: 

See clock() function.
http://www.cplusplus.com/reference/clibrary/ctime/clock/

const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) /  CLOCKS_PER_SEC;

If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not secconds ).

EDIT:
responsible header files - <ctime> or <time.h>

bb
When I run this code, a get a huge number, no idea what it means. I'd like something that says "9.334 seconds".
Jack BeNimble
Don't forget to #include <ctime> or <time.h> appropriately so that clock() gets an appropriate prototype and clock_t is defined.
RBerteig
Keep in mind that even though clock() returns a number of milliseconds, the precision of clock() can be much worse than that. Fir instance in Windows the precision of the clock() function is something like 40 ms.
John Dibling
+4  A: 

Just a side note: if you're running on Windows, and you really really need precision, you can use QueryPerformanceCounter. It gives you time in (potentially) nanoseconds.

v3
+1  A: 

Get the system time in milliseconds at the beginning, and again at the end, and subtract.

To get the number of milliseconds since 1970 in POSIX you would write:

struct timeval tv;

gettimeofday(&tv, NULL);
return ((((unsigned long long)tv.tv_sec) * 1000) +
        (((unsigned long long)tv.tv_usec) / 1000));

To get the number of milliseconds since 1601 on Windows you would write:

SYSTEMTIME systime;
FILETIME filetime;

GetSystemTime(&systime);
if (!SystemTimeToFileTime(&systime, &filetime))
    return 0;

unsigned long long ns_since_1601;
ULARGE_INTEGER* ptr = (ULARGE_INTEGER*)&ns_since_1601;

// copy the result into the ULARGE_INTEGER; this is actually
// copying the result into the ns_since_1601 unsigned long long.
ptr->u.LowPart = filetime.dwLowDateTime;
ptr->u.HighPart = filetime.dwHighDateTime;

// Compute the number of milliseconds since 1601; we have to
// divide by 10,000, since the current value is the number of 100ns
// intervals since 1601, not ms.
return (ns_since_1601 / 10000);

If you cared to normalize the Windows answer so that it also returned the number of milliseconds since 1970, then you would have to adjust your answer by 11644473600000 milliseconds. But that isn't necessary if all you care about is the elapsed time.

Jared Oberhaus
+10  A: 

I would seriously consider the use of Boost, particularly boost::posix_time::ptime and boost::posix_time::time_duration (at http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time.html).

It's cross-platform, easy to use, and in my experience provides the highest level of time resolution an operating system provides. Possibly also very important; it provides some very nice IO operators.

To use it to calculate the difference in program execution (to microseconds; probably overkill), it would look something like this [browser written, not tested]:

ptime time_start(microsec_clock::local_time());
//... execution goes here ...
ptime time_end(microsec_clock::local_time());
time_duration duration(time_end - time_start);
cout << duration << '\n';
Jeremy CD
+2  A: 

just in case you are on Unix, you can use time to get the execution time:

$ g++ myprog.cpp -o myprog
$ time ./myprog
fengshaun
+1  A: 

For Mac OS X, see http://developer.apple.com/qa/qa2004/qa1398.html

Kristopher Johnson
Just what I was looking for :)Thank you
Asad Khan
+2  A: 

In Windows: use GetTickCount

//GetTickCount defintition
#include <windows.h>
int main()
{

    DWORD dw1 = GetTickCount();

    //Do something 

    DWORD dw2 = GetTickCount();

    cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;

}
aJ
+1  A: 

You can also use the clock_gettime. This method can be used to measure:

  1. System wide real-time clock
  2. System wide monotonic clock
  3. Per Process CPU time
  4. Per process Thread CPU time

'

#include < time.h >

int main(){

timespec ts_beg, ts_end;

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);

std::cout << ( (ts_end.tv_sec - ts_beg.tv_sec) * 1e9) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";

`