Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / iOS

Wink of an Eye

4.86/5 (3 votes)
20 Oct 2015CPOL 6.9K   23  
Working with High Resolution time on iOS

Introduction

I needed a high resolution time API because I wanted to check whether some optimization in my code really leads to a better performance and I found it in the mach time-API. 

Background

Normally the NSLog -timestamps are fine, but here were the same milliseconds, so I searched for some other methods. But a nanoseconds is a millionstel part of a millisecond.

Using the Code

I destilled the code in that way so anybody can use it. In the zip is only the code as given below:

Objective-C
#include <mach/mach_time.h>

static mach_timebase_info_data_t info = {0};
	if( info.denom == 0) { //do once
		mach_timebase_info(&info);
	}

	UInt64 start = mach_absolute_time();
	NSLog(@"Do some short duration work");
	UInt64 ende = mach_absolute_time();
	UInt64 nanos = ((ende - start) * info.numer) / info.denom;
	NSLog(@"Duration in nano seconds: %lld, that are %f milli-seconds",
	        nanos, (float) nanos / 1000000. );

For extended use, it would be interesting to initialize in a common way and to find better ways for output and statistics.

Points of Interest

It is interesting to find a way to get such a precise timing which sensibly measures the time.

History

  • 20.10.2015: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)