获得当前系统时间毫秒的最佳方法是什么?


当前回答

到目前为止,我发现gettimeofday在iOS (iPad)上是一个很好的解决方案,当你想执行一些间隔评估(比如帧速率,渲染帧的计时……):

#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);

其他回答

NSTimeInterval time = ([[NSDate date] timeIntervalSince1970]); //double
long digits = (long)time; //first 10 digits        
int decimalDigits = (int)(fmod(time, 1) * 1000); //3 missing digits
/*** long ***/
long timestamp = (digits * 1000) + decimalDigits;
/*** string ***/
NSString *timestampString = [NSString stringWithFormat:@"%ld%03d",digits ,decimalDigits];

我需要一个NSNumber对象,包含[[NSDate date] timeIntervalSince1970]的确切结果。因为这个函数被调用了很多次,我并不真的需要创建一个NSDate对象,性能不是很好。

所以要得到原始函数给我的格式,试试这个:

#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
double perciseTimeStamp = tv.tv_sec + tv.tv_usec * 0.000001;

这应该给你完全相同的结果[[NSDate date] timeIntervalSince1970]

// Timestamp after converting to milliseconds.

NSString * timeInMS = [NSString stringWithFormat:@"%lld", [@(floor([date timeIntervalSince1970] * 1000)) longLongValue]];

CFAbsoluteTimeGetCurrent ()

Absolute time is measured in seconds relative to the absolute reference date of Jan 1 2001 00:00:00 GMT. A positive value represents a date after the reference date, a negative value represents a date before it. For example, the absolute time -32940326 is equivalent to December 16th, 1999 at 17:54:34. Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.

[[NSDate date] timeIntervalSince1970];

它以双精度返回自epoch以来的秒数。我几乎可以肯定你可以从小数部分访问毫秒。