On Jul 21, 2011, at 7:59 PM, Eric E. Dolecki wrote:

> I'm curious if there is a way to NSLog how long some code takes to execute
> (outside of using Instruments).
> 
> In Flash one can use getTimer and see how much time passed inline. Is there
> a way to do this in Obj-C?
> 
> Would one use a NSDate object?


For better accuracy, you may use function mach_absolute_time().

For example:

#include <mach/mach.h>
#include <mach/mach_time.h>

static uint64_t absoluteTimeToNanoseconds(uint64_t t) 
{    
    static mach_timebase_info_data_t sTimebaseInfo; // (note: static data will 
be zero initialized)
    
    // setup the mach timebase info
    if ( sTimebaseInfo.denom == 0 ) {
        (void) mach_timebase_info(&sTimebaseInfo);
    }
    uint64_t elapsedNano = t * sTimebaseInfo.numer / sTimebaseInfo.denom;
    return elapsedNano;
}


void foo() 
{
        uint64_t t0 = mach_absolute_time();
        // do some stuff …      
        // ...
        uint64_t t1 = mach_absolute_time();

        uint64_t elapsedNanoseconds = absoluteTimeToNanoseconds(t1 - t0);
        NSLog(@"Elapsed time: %.2f ms", elapsedNanoseconds*1e-6];
}





There is also the tool "time" (see man time(1)) which can be used to measure 
runtime of executables running in the console.



_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to