Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
157 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
",end - start);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...