tags:

views:

99

answers:

3

I have tried clock_gettime(CLOCK_REALTIME) and gettimeofday() without luck - And the most basic like clock(), what return 0 to me (?).

But none of they count the time under sleep. I don't need a high resolution timer, but I need something for getting the elapsed time in ms.

Thanks.

EDIT: Final program:

#include <iostream>
#include <string>
#include <time.h>
#include <sys/time.h>
#include <sys/resource.h>

using namespace std;

// Non-system sleep (wasting cpu)
void wait ( int seconds )
{
  clock_t endwait;
  endwait = clock () + seconds * CLOCKS_PER_SEC ;
  while (clock() < endwait) {}
}

int show_time() {
    timeval tv;
    gettimeofday(&tv, 0);
    time_t t = tv.tv_sec;
    long sub_sec = tv.tv_usec;

    cout<<"t value: "<<t<<endl;
    cout<<"sub_sec value: "<<sub_sec<<endl;
}

int main() {
    cout<<show_time()<<endl;
    sleep(2);
    cout<<show_time()<<endl;
    wait(2);
    cout<<show_time()<<endl;
}
+4  A: 

You need to try gettimeofday() again, it certainly count the wall clock time, so it counts when the process sleep as well.

long long getmsofday()
{
   struct timeval tv;
   gettimeofday(&tv);
   return (long long)tv.tv_sec*1000 + tv.tv_usec/1000;
}


...

long long start = getmsofday();
do_something();
long long end = getmsofday();

printf("do_something took %lld ms\n",end - start);
nos
It's worth noting that <unistd.h> is needed for gettimeofday.
I have rechecked it and I have gotten it to work perfectly with gettimeofday! I think I was doing something bad... I'll update the question with my final test program. Thanks!
NeDark
It should be `tv.tv_sec*1000 + ..`
rudi-moore
+2  A: 

Your problem probably relates to integral division. You need to cast one of the division operands to float/double to avoid truncation of decimal values less than a second.

clock_t start = clock();
// do stuff

// Can cast either operand for the division result to a double.
// I chose the right-hand operand, CLOCKS_PER_SEC.
double time_passed = clock() / static_cast<double>(CLOCKS_PER_SEC);

[Edit] As pointed out, clock() measures CPU time (clock ticks/cycles) and is not suitable well-suited for wall timer tests. If you want a portable solution for that, @see Boost.Timer as a possible solution

+1  A: 

You actually want clock_gettime(CLOCK_MONOTONIC, ...).

Matt Joiner