• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: sleep() drift
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: sleep() drift


  • Subject: Re: sleep() drift
  • From: Greg Parker <email@hidden>
  • Date: Thu, 4 Jun 2009 13:22:18 -0700

On Jun 4, 2009, at 5:39 AM, email@hidden wrote:
I am facing an issue in use of mach_absolute_time().

mach_absolute_time() gives drift even when NTP timing update is on.

Please see my code below:

#import <Cocoa/Cocoa.h>
#import <mach/mach_time.h>
nt main(int argc, char *argv[])
{
	uint64_t nowTime = mach_absolute_time();
	uint64_t drift = 0;
	for (int i=0;i<1000;i++)
	{
		sleep(5);
		uint64_t current_Time = mach_absolute_time();
		uint64_t differenceTime = (current_Time - nowTime)*1E-6;
		drift = differenceTime - (i+1)*5000;
		NSLog(@"Elapsed Time =%lld",differenceTime);
		NSLog(@"drift =%lld",drift);
	}
	return 1;
   //return NSApplicationMain(argc,  (const char **) argv);
}

Expected Results:
I expected to see zero drift in the print. After several runs, the drift
kept on increasing

Your expectation is wrong. sleep() will sleep for 5000 milliseconds. But (1) there's no guarantee that your thread gets to run at the 5001st millisecond, and (2) your timing and printing code itself takes non-zero time.


If you really want to run every 5000 milliseconds with no drift, you'll need to use a more careful sleep mechanism (starting with nanosleep() plus accounting for the non-sleep time). A proper timer like NSTimer or CFRunLoopTimer might also work; they won't drift, but their jitter might be too high for your purposes.


-- Greg Parker email@hidden Runtime Wrangler


_______________________________________________

Cocoa-dev mailing list (email@hidden)

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:
This email sent to email@hidden


References: 
 >NSNull and distinct objective-C type (From: Steven Hamilton <email@hidden>)
 >Re: NSNull and distinct objective-C type (From: email@hidden)

  • Prev by Date: Re: NSNull and distinct objective-C type
  • Next by Date: Re: NSNull and distinct objective-C type
  • Previous by thread: Re: NSNull and distinct objective-C type
  • Next by thread: Re: NSNull and distinct objective-C type
  • Index(es):
    • Date
    • Thread