开发者

How do I record timestamps in a Mac OS X C++ program?

开发者 https://www.devze.com 2022-12-18 07:56 出处:网络
I\'m running a giant simulation / with a graphics engine. There are lots of events that are flying by.

I'm running a giant simulation / with a graphics engine.

There are lots of events that are flying by.

I would like to timestamp them (measured in milliseconds since the start of program executio开发者_开发技巧n).

What should I be using for this? [What library?]


Since Mac OS X is Unix based, try gettimeofday(). It will return seconds and microseconds, up to the resolution of the system clock.

#include <sys/types.h>    
int gettimeofday(struct timeval *tv, struct timezone *tz);

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


gettimeofday() will mostly work okay, but it is subject to anomalies, e.g. when the user changes the system date/time. A better method would be this:

#include <CoreServices/CoreServices.h>

unsigned long long GetTimeSinceBootInMilliseconds()
{
   UnsignedWide uw = AbsoluteToNanoseconds(UpTime());
   return ((((unsigned long long)uw.hi)<<32)|(uw.lo))/1000000;
}

Note that the values returned by this function will be milliseconds-since-boot, so if you want milliseconds-since-program-start, call this method once at program start, store that value, and subtract it from the later results.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号