tags:

views:

352

answers:

5

This will show how many seconds:

#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
    int times,timed;

    times=time(NULL);
    //CODE HERE

    timed=time(NULL);
    times=timed-times;
    cout << "time from start to end" << times;
}

This will show how many ticks:

#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
    int times,timed;

    times=clock();
    //CODE HERE

    timed=clock();
    times=timed-times;
    cout << "ticks from start to end" << times;
}

How do I get milliseconds?

+4  A: 

If you use a Unix OS, like Linux or Mac OS X, you can go to the command line and use the line

time call-program

The time command times how long the execution of any command line takes, and reports that to you.

I don't know if there's something like that for Windows, nor how you can measure miliseconds inside a C/C++ program, though.

jpmelos
+3  A: 

Refer to question "Convert Difference between 2 times into Milliseconds" on Stack Overflow.

Or use this:

static double diffclock(clock_t clock1,clock_t clock2)
{
    double diffticks=clock1-clock2;
    double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
    return diffms;
}
sat
+1  A: 

There's a CLOCKS_PER_SEC macro to help you convert ticks to milliseconds.

There are O/S-specific APIs to get high-resolution timers.

You can run your program more than once (e.g. a 1000 times) and measure that using a low-resolution timer (e.g. some number of seconds), and then divide that total by the number of times you ran it to get a (higher-resolution) average time.

ChrisW
+1  A: 

In Windows, you can use GetTickCount, which is in milliseconds.

JRL
"The resolution of the GetTickCount function is limited to the resolution of the system timer, which is typically in the range of 10 milliseconds to 16 milliseconds."
ChrisW
@ChrisW: there was no specification that the resolution should be higher.
JRL
You're right; I'm just warning the OP that although `GetTickCount` returns a value that's measured in milliseconds, it isn't accurate to the nearest millisecond: instead it's accurate to the nearest 'tick' which is what he already had (and was trying to get away from) in his OP.
ChrisW
+1  A: 

Under Win32, you can access the high-resolution timer using QueryPerformanceFrequency and QueryPerformanceCounter (IMHO that should be preferred, possibly with fallback to GetTickCount). You can find the example in Community Content section on MSDN.

PiotrLegnica