High Res Timer
Volume Number: 8
Issue Number: 1
Column Tag: c workshop
A High-Resolution Timer
A simple package for measuring small intervals of time for
performance analysis
By Martin Minow, Arlington, Massachusetts
Note: Source code files accompanying article are located on MacTech CD-ROM orsource code disks.
Volume 6 of Inside Macintosh - which is to say late System 6.0 and System 7 -
describes the extended TimeManager and a drift-free timer function that lets an
application measure durations with a finer resolution than the 1/60 second system tick
count.
In order to simplify measuring small intervals for performance analysis, I
wrote a simple package that allows recording the “time of day” at its highest resolution.
Using this as a base, you can record the start and end of an event of interest (such as a
subroutine call) and, by using one of the subroutines in the package, determine the
elapsed time.
For my particular purposes, elapsed times are recorded in integers with
microsecond resolution, giving a maximum interval of just over 35 minutes, since 231
is greater than (35 * 60 * 1000000). If you need to record longer intervals, you need
only redo the DeltaTime subroutine (as shown in the demo application) so it returns a
floating-point (double-precision) value.
The demo program shows some of the calls and lets you get an idea of the amount
of time needed to setup and call the timer service. On my Macintosh IIci with the THINK
C debugger enabled, the average time is about 160µsec, which is not shabby at all. Of
course, you should not assume that microsecond resolution means microsecond
accuracy.
InitializeMicrosecondTimer will return an error if the drift-free timer is not
supported on your system. Because of the way it calls Gestalt, you must compile it on a
modern system (THINK C 5.0) as the “glue” that calls Gestalt now includes code to check
for the Gestalt trap presence.
In order to ensure that the timer routine’s periodic task is removed when your
application exits, InitializeMicrosecondTimer patches the ExitToShell trap for the
removal function. Because of the way THINK C installs its own ExitToShell trap, be sure
to call InitializeMicrosecondTimer before calling any THINK C routines from the
standard I/O or THINK Class libraries.
Acknowledgments
This is a revision of a program I first wrote for the IBM 7090 in 1964. OK,
maybe it was 1965. Some of the Macintosh specific code can be traced to a timing
routine in the MacDTS “FracApp” demonstration program by Keith Rollin and Bo3b
Johnson, while the exit handler is based on code in the atexit function in the THINK C
library.
Listing: MicrosecondTimer.h
/* MicrosecondTimer.h */
/*
* Time measurement.
* Copyright © 1991 Martin Minow. All Rights Reserved
*
/*
* Definitions for the Millisecond timer
*/
#ifndef _H_MsecTimer
#define _H_MsecTimer
#define MSEC_PER_TICK 1
typedef struct MicrosecondEpoch {
unsigned long time; /* Time of day */
signed long microsecond; /* Residual */
} MicrosecondEpoch, *MicrosecondEpochPtr;
/*
* Initialize the clock - call once when your
* application starts.
*/
OSErr InitializeMicrosecondTimer(void);
/*
* Cancel the clock - this is called automatically
* when your application exits.
*/
void CancelMicrosecondTimer(void);
/*
* Return the current extended time value.
*/
void GetEpoch(MicrosecondEpochPtr result);
/*
* Compute the difference between two epoch's. The
* result is in deltaTime (in microseconds).
* deltaTime is positive if epoch2 is later than epoch1.
*
* Returns TRUE if the time can be represented in
* microseconds (less than 35 minutes difference).
* If it returns FALSE, deltaTime is likely to be garbage.
*/
Boolean DeltaTime(
MicrosecondEpochPtr epoch1,
MicrosecondEpochPtr epoch2,
signed long *deltaTime
);
/*
* Compute the difference between two epoch's. The
* result is returned as a floating-point number
* of seconds.
*/
double DoubleDelta(
MicrosecondEpoch *start,
MicrosecondEpoch *finish
);
/*
* Format an epoch value as "hh:mm:ss.fraction
*/
void EpochToString(
MicrosecondEpochPtr epochPtr,
StringPtr result
);
/*
* Use an extended time value to adjust the
* local clock. Unfortunately, we can only adjust
* the clock by an integral number of seconds.
*/
void AdjustClock(
signed long adjustment
);
#endif
Listing: MicrosecondTimer.c
/* MicrosecondTimer.c */
/*
* Time measurement.
* Copyright © 1991 Martin Minow. All Rights Reserved
*
* This function creates a high-resolution "time of day
* timer that is (or, at least, ought to be) synchronized
* with the system time of day value. It uses the
* new time manager calls.
*
* In order to keep our timer in reasonable synchronization
* with the system time of day, we shadow that value at
* each time-of-day trap.
*
* Usage:
* InitializeMicrosecondTimer(void);
* Call this - once - when your program starts. It
* installs the timer interrupt routine. It returns
* noErr if successful, or unimpErr if the Extended
* Time Manager is not supported on this system.
*
* Important: if you are using the THINK C ANSI,
* console, or class libraries, be sure to call
* InitializeMicrosecondTimer before calling any
* THINK C routines. Otherwise, your program
* may crash on exit under certain ill-defined
* circumstances.
*
* CancelMicrosecondTimer(void)
* This must be called before your application exits.
* InitializeMSecTimer() establishes an exit handeler
* to force its call, so you needn't worry about it.
*
* GetEpoch(
* MicrosecondEpoch *result
* )
* Call this to get the time of day. The result
* consists of a time (seconds) value that is
* intended to track GetTimeOfDay exactly, extended
* by the number of microseconds past this second.
*
* DeltaTime(
* MicrosecondEpoch *startTime,
* MicrosecondEpoch *endTime
* signed long *difference
* )
* Compute the difference between two extended
* time values, returning the result in the third
* parameter (as a signed number of microseconds).
* The result will be positive if time2 is later
* than time1. DeltaTime returns TRUE if the
* absolute value of the difference (in seconds)
* is less than 35 minutes (a signed longword can
* resolve a 34 minute interval). (You might want
* to redo this to return a double-precision format
* value, rather than a longword.)
*
* DoubleDelta(
* MicrosecondEpoch *start,
* MicrosecondEpoch *finish
* )
* Compute the difference between two extended
* time values, returning the result as a double-
* precision number of seconds.
*
* EpochToString(
* MicrosecondEpoch *epoch
* Str255 result
* )
* Convert an extended time value to a fixed-width,
* fixed-format Pascal string "hh:mm:ss.fraction".
*
* Although the code has not been tested under MPW, it
* ought to port easily: just re-do the asm stuff.
*
* Acknowledgements:
* Parts of the time manager calls are based on a
* timing module in the MacDTS FracApp demo program
* by Keith Rollin an Bo3b Johnson.
*
* The exit handler is based on similar code in the
* atexit() function in the THINK C support library.
*/
#include
#ifndef THINK_C
#include
#endif
#include
#include
#include "MicrosecondTimer.h
/*
* This is needed to establish an exit trap handler.
*/
typedef void (*MyProcPtr)(void);
typedef struct {
short jmp;
MyProcPtr function;
} JumpVector;
static void *oldExitVector;
static JumpVector *jumpVector;
static void TimerExitHandler(void);
#define MILLION (1000000L)
/*
* This is a time manager record, extended to include a
* shadow copy of the system time of day value that is
* updated once a second.
*/
typedef struct TimeInfoRecord {
TMTask TMTask; /* The task record */
unsigned long epoch; /* Time of day info */
} TimeInfoRecord, *TimeInfoPtr;
static TimeInfoRecord gTimeInfo;
#define TIME (gTimeInfo.TMTask)
static long gOverheadTime;
static pascal void TimeCounter(void);
static void Concat(StringPtr dst, StringPtr src);