Quantcast
Viewing all articles
Browse latest Browse all 8

Answer by Wayne Uroda for Getting time elapsed in Objective-C

For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.

Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476

In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime!

I also benchmarked the mach_timebase_info call and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.

#include <mach/mach.h>#include <mach/mach_time.h>uint64_t getTickCount(void){    mach_timebase_info_data_t sTimebaseInfo;    uint64_t machTime = mach_absolute_time();    // Convert to milliseconds    mach_timebase_info(&sTimebaseInfo);    machTime *= sTimebaseInfo.numer;    machTime /= sTimebaseInfo.denom;    machTime /= 1000000; // convert from nanoseconds to milliseconds    return machTime;}

Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3.

The solution using CACurrentMediaTime() is quite trivial:

uint64_t getTickCount(void){    double ret = CACurrentMediaTime();    return ret * 1000;}

Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>