Getting more accurate time measurement
Currently I'm recording the time between two events in decimal minutes using :
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
CGFloat hour = [dateComponents hour];
CGFloat minute = [dateComponents minute];
CGFloat second = [dateComponents second];
//set start time in decimal minutes
CGFloat startTime = ((hour*3600.0)+(minute*60.0)+(second))*.016666;
//do work...
//set end time in decimal minutes
CGFloat endTime = ((hour*3600.0)+(minute*60.0)+(second))*.016666;
//calculate time elapsed in decimal minutes
CGFloat totalTime = endTime-startTime;
The issue that I'm having is that I am really only getting the time in seconds and then converting to decimal minutes. So, the only values that I'm getting are 0.016663
开发者_开发问答(one second in decimal minutes), 0.033325
(two seconds in decimal minutes), 0.049988
(three seconds in decimal minutes), etc. I'm not getting any values in between. Is there any way I can get a more accurate time? I checked to see if NSDateComponents
has a millisecond
property or whatnot, but I couldnt find any.
Thanks!
You can also use CFAbsoluteTimeGetCurrent() which returns a double containing time in seconds and fractions of a second:
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
Then later you can compute an elapsed time in seconds and fractions of a second:
elapsed = CFAbsoluteTimeGetCurrent() - startTime;
NSLog(@"Elapsed Time: %0.3f seconds", elapsed);
I like to have debug code (#ifdef DEBUG) in my app delegate and in viewDidAppear in my first view controller to report the elapsed startup time so I can keep an eye on that while developing.
Why not just use NSDate?
NSDate *date1, *date2;
NSTimeInterval timeInSeconds;
date1 = [NSDate date];
// Do work
date2 = [NSDate date];
timeInSeconds = [date2 timeIntervalSinceDate:date1];
// Or, without using date2:
timeInSeconds = -[date1 timeIntervalSinceNow];
That should give your measurement sub-second accuracy.
If you want to get Unix-y, you can use gettimeofday
(reference):
struct timeval tv;
gettimeofday(&tv, NULL);
NSLog(@"seconds: %d, microseconds: %d\n", tv.tv_sec, tv.tv_usec);
Be sure to add #import <sys/time.h>
to your file
Or if you really want to get down the metal, you can use mach_absolute_time()
, as per this SO Q/A and/or Apple docs.
精彩评论