views:

817

answers:

4

Hi,

Is there a more Object Oriented alternative to using gettimeofday() in C++ on linux? I like for instance to be able to write code similar to this:

DateTime now = new DateTime;
DateTime duration = new DateTime(2300, DateTime.MILLISECONDS)
DateTime deadline = now + duration;

while(now < deadline){
    DoSomething();
    delete now;
    now = new DateTime()
}

The target is an embedded linux system and there are no Boost libraries, but maybe there is something that is easy to port (something implemented with header files only for example).

A: 

I think you should be fine with using stuff from ctime

#include <ctime>

time
difftime
mktime

should do the job in a very portable way. cplusplus.com

Totonga
I looked at this but the resolution is too coarse. I want to get down to millisecond resolution.
mikelong
+3  A: 

There is no object-oriented interface for dealing with time and intervals that's part of the standard C++ library.

You might want to look at Boost.Date_Time though. Boost is useful and well written that its practically a part of the standard C++ library.

Omnifarious
A: 
/usr/include/linux/time.h 

gives structure :-

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

on Linux, may be you could use it...

essbeev
A: 

So porting boost wasn't an option for my target. Instead I had to go with gettimeofday(). There are however some nice macros for dealing with timeval structs in sys/time.h

#include <sys/time.h>

void timeradd(struct timeval *a, struct timeval *b,
          struct timeval *res);

void timersub(struct timeval *a, struct timeval *b,
          struct timeval *res);

void timerclear(struct timeval *tvp);

void timerisset(struct timeval *tvp);

void timercmp(struct timeval *a, struct timeval *b, CMP);

It took a while to find them though because they weren't in the man pages on my machine. See this page: http://linux.die.net/man/3/timercmp

mikelong