0

I have a queue with structs. This struct includes the exact time of pushing itself into queue

I have something like this to see system time:

time_t rawtime;
struct tm * timeinfo;

time ( &rawtime );
timeinfo = localtime ( &rawtime );

long callTime=timeinfo->tm_hour*3600+timeinfo->tm_min*60+timeinfo->tm_sec;
q.push( Call( callNum, callTime, callLength ));

The problem is when I pop next struct from the queue, I wanna calculate how much long struct waited in queue in milliseconds.

I hope someone can get what I wanna say.. :\

Tim
  • 20,184
  • 24
  • 117
  • 214
  • What problem are you actually having? The code that you've given compiles just fine. – JSBձոգչ May 17 '11 at 18:07
  • 1
    you can get microseconds with gettimeofday on unixes – Kevin May 17 '11 at 18:09
  • timer() is not a millisecond timer - its granularity is 1 second. You may want to look at the standard ctime() function, or consider operating system specific stuff. –  May 17 '11 at 18:10

3 Answers3

3

You can use gettimeofday and then subtract the time stored in your queue element. gettimeofday() can provide time resolution in milliseconds. You can check this SO link for more info.

This is assuming that every element in the stack also stores the time that it was pushed in. If the element doesn't have it, you can either store a structure with the element and the time or have a separate stack with the times alone.

Community
  • 1
  • 1
Gangadhar
  • 1,893
  • 9
  • 9
  • C:\vy2\main.cpp|37|error: 'timeval' was not declared in this scope| btw. #include is already typed. –  May 17 '11 at 18:17
1

You need to use the function gettimeofday() rather than time(). The former supports sub-millisecond precision, while the latter is only accurate to the nearest second.

JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
  • 2
    Not part of standard C++, so his platform may or may not have it. –  May 17 '11 at 18:15
  • @WhoCares No, it doesn't - it's a POSIX thing not supported by windows. –  May 17 '11 at 18:45
  • I just need to add milisecond to this line: long callTime=timeinfo->tm_hour*3600+timeinfo->tm_min*60+timeinfo->tm_sec I mean something like tm_msec :\ –  May 17 '11 at 18:50
  • @WhoCares We know what you want, and we are telling you there is no portable way to do it! –  May 17 '11 at 18:52
  • I think it can be with clocks_per_sec but i just cant calculate it in my mind. im totally collapsed. somebody help pls:) –  May 17 '11 at 18:53
0

gettimeofday is a answer, but if you want just check how long your item was in queue clock_gettime() could be more suitable. For example, you could use CLOCK_MONOTONIC (suppose we do not count sec):

struct timespec ts;
clock_gettime(CLOCK_MONOTONIC,&ts);
// do some action ....
struct timespec ts2;
clock_gettime(CLOCK_MONOTONIC,&ts2);
std::cout << "spend " << ts2.tv_nsec - ts.tv_nsec << " nanoseconds" << std::endl;

And, of course, clock_gettime is not part of C++, it is part of POSIX.1-2008

tvn
  • 634
  • 3
  • 6