简体   繁体   中英

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

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 execution).

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM