Stopwatch timing in Cocoa
Posted on May 24, 2008 at 9:00 am by Late Night Coder
Sometimes you want to time things in your code. The usual pattern is to store the current time, do something, store the current time, compute the difference, and then convert it to something useful, like seconds elapsed. That pattern gets old fast, so here’s a little Cocoa stopwatch class that neatly encapsulates stopwatch timing on Mac OS X.
To obtain the most accurate timing information, you want to get the current time using a method that has low overhead and high precision. The lowest overhead, highest precision time function on Mac OS X is mach_absolute_time(). It returns the current clock time in a CPU dependent time unit (clock ticks or something similar), so you have to convert it to a real world value. For details, see this post on the carbon-dev mailing list, or this article from Apple Technical Q&A.
Based on that, here’s the code for the LNCStopwatch class:
LNCStopwatch.h Show Code
LNCStopwatch.m Show Code
The API for the LNCStopwatch class is really simple. It supports starting the stopwatch, stopping the stopwatch, resetting the stopwatch, and getting the number of seconds elapsed as a decimal. Here’s an example code snippet:
LNCStopwatch* stopwatch = [[LNCStopwatch alloc] init]; double elapsed; [stopwatch start]; // DO SOMETHING THAT TAKES SOME TIME [stopwatch stop]; elapsed = [stopwatch elaspedSeconds]; [stopwatch reset]; [stopwatch start]; // DO SOMETHING THAT TAKES SOME TIME elapsed = [stopwatch elaspedSeconds]; // DO SOMETHING THAT TAKES SOME TIME elapsed = [stopwatch elaspedSeconds]; [stopwatch stop];
Ian Wagner wrote:
Thanks so much! Very helpful article!
Posted on 09-Jun-08 at 10:47 am
Jesse Hemingway wrote:
Excellent little class, I’m new to MacOS programming and this one’s a gem that saved me a chunk of research.
Posted on 22-Oct-08 at 11:40 am