Friday, December 08, 2006

[Tip] When you must be precise be mach precise

Just thought i'd post a playful little tidbit. One of the things you should be as a programmer is playful and experimental. And todays tip I originally learned from Aaron Hillegass (yes the guy who write Cocoa Programming for Mac OS X) at the Student WWDC 06 Session, though you can find it documented on Apples site easily. One of the things I do is play around with parts of a language i don't normally use to see what it's usefull for and sometimes test what benifets (if any) there are to it. One of the things I try to do from time to time is evaluate the speed of particular language features or methods in my apps. Probably the most accurate way to do this is to dig into the kernel and take time measurements in nanoseconds and that's what this simple little app does
#include < stdio.h> #include < stdarg.h> #include < mach/mach.h> #include < mach/mach_time.h> #include < unistd.h> int main() { uint64_t start = mach_absolute_time(); //you can do whatever you want between this... int i; for(i = 0; i < 2000; i++) { int l = 233 << 1; printf("\n\n%i\n\n",l); } //and here where we take the 2nd time measurement... uint64_t end = mach_absolute_time(); uint64_t elapsed = end - start; mach_timebase_info_data_t info; mach_timebase_info(&info); uint64_t nanoSeconds = elapsed * info.numer / info.denom; printf ("elapsed time was %lld nanoseconds\n", nanoSeconds); return 0; }
in this case there isn't anything really important going in in this little test example, but you get the point of what benifets this can hold for you if you use it right.

1 comment:

  1. This is one of two ways. The other is Mach clocks, which I described on my blog.

    ReplyDelete