How do I compute, as an integer, the number of milliseconds between now and the previous time I remembered as now?
Is there any reason you need it as an integral number of milliseconds? Asking NSDate for the time interval since another date will give you a floating-point number of seconds. If you really do need milliseconds, you can simply multiply by that by 1000 to get a floating-point number of milliseconds. If you really do need an integer, you can round or truncate the floating-point value.
If you'd like to do it with integers from start to finish, use either UpTime
or mach_absolute_time
to get the current time in absolute units, then use AbsoluteToNanoseconds
to convert that to a real-world unit. Obviously, you'll have to divide that by 1,000,000 to get milliseconds.
QA1398 suggests mach_absolute_time
, but UpTime
is easier, since it returns the same type AbsoluteToNanoseconds
uses (no “pointer fun” as shown in the technote).
AbsoluteToNanoseconds
returns an UnsignedWide
, which is a structure. (This stuff dates back to before Mac machines could handle scalar 64-bit values.) Use the UnsignedWideToUInt64
function to convert it to a scalar. That just leaves the subtraction, which you'll do the normal way.