1

If I have:

double now_ms() {
    return 1000 * (float)[[NSDate date] timeIntervalSince1970];
};

:
    NSLog( @"%f", now_ms() ); // inside a CADisplayLink tick-event

It gives the same value each time.

I can fix this by making a Lambda:

double (^now_ms)(void) = ^() {
    return 1000.f * [[NSDate date] timeIntervalSince1970];
};
NSLog( @"%f", now_ms() ); // works!

However I would prefer it to be a free function.

What is going on?

I suspect this is some kind of run-time optimisation.

P i
  • 29,020
  • 36
  • 159
  • 267

1 Answers1

1

The issue is that NSTimeInterval (which is what timeIntervalSince1970 returns) is a double and you’re casting it to a float. But float can only capture roughly 7 significant digits. That’s not nearly accurate enough to capture the number of seconds since 1970, much less the number of milliseconds.

Your lambda solution works simply because you removed the float cast. You can do the same with your function:

double now_ms() {
    return 1000.0 * [[NSDate date] timeIntervalSince1970];
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044