Accuracy of NSTimer - objective-c

I am trying to use NSTimer to create a Stop-watch style timer that increments every 0.1 seconds, but it seems to be running too fast sometimes ..
This is how I've done it:
Timer =[NSTimer scheduledTimerWithTimeInterval: 0.1 target:self selector:#selector(updateTimeLabel) userInfo:nil repeats: YES];
and then:
-(void)updateTimeLabel
{
maxTime=maxTime+0.1;
timerLabel.text =[NSString stringWithFormat:#"%.1f Seconds",maxTime];
}
This will display the value of the timer in the Label, and I can later utilize maxTime as the time when the Timer is stopped ...
THe problem is that it runs very inaccurately.
Is there a method where I can make sure that NSTimer fires strictly every 0.1 seconds accurately ? I know that NSTimer isn't accurate , and I'm asking for a tweak to make it accurate.
THanks

According to the NSTimer documentation, it is not meant to be accurate.
Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs during a long callout or while the run loop is in a mode that is not monitoring the timer, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.
You may want to use the dispatch_after function from GCD, which is suggested by the official documentation for this exact purpose (creating a timer).
If you want to perform a block once after a specified time interval, you can use the dispatch_after or dispatch_after_f function.
By the way, I agree with Caleb's answer. You probably are going to solve your problems if you don't accumulate error like your doing right now.
If you store the start date and recalculate the time at every iteration using the -timeIntervalSince: method, you're gonna end up with an accurate UI update, regardless of the timer precision.

Here's a class you can use to do what you want:
#interface StopWatch()
#property ( nonatomic, strong ) NSTimer * displayTimer ;
#property ( nonatomic ) CFAbsoluteTime startTime ;
#end
#implementation StopWatch
-(void)dealloc
{
[ self.displayTimer invalidate ] ;
}
-(void)startTimer
{
self.startTime = CFAbsoluteTimeGetCurrent() ;
self.displayTimer = [ NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:#selector( timerFired: ) userInfo:nil repeats:YES ] ;
}
-(void)stopTimer
{
[ self.displayTimer invalidate ] ;
self.displayTimer = nil ;
CFAbsoluteTime elapsedTime = CFAbsoluteTimeGetCurrent() - self.startTime ;
[ self updateDisplay:elapsedTime ] ;
}
-(void)timerFired:(NSTimer*)timer
{
CFAbsoluteTime elapsedTime = CFAbsoluteTimeGetCurrent() - self.startTime ;
[ self updateDisplay:elapsedTime ] ;
}
-(void)updateDisplay:(CFAbsoluteTime)elapsedTime
{
// update your label here
}
#end
The key points are:
do your timing by saving the system time when the stop watch is started into a variable.
when the the stop watch is stopped, calculate the elapsed time by subtracting the stop watch start time from the current time
update your display using your timer. It doesn't matter if your timer is accurate or not for this. If you are trying to guarantee display updates at least every 0.1s, you can try setting your timer interval to 1/2 the minimum update time (0.05s).

maxTime=maxTime+0.1;
This is the wrong way to go. You don't want to use a timer to accumulate the elapsed time because you'll be accumulating error along with it. Use the timer to periodically trigger a method that calculates the elapsed time using NSDate, and then updates the display. So, change your code to do something instead:
maxTime = [[NSDate date] timeIntervalSince:startDate];

NSTimer is not guaranteed to be accurate, although in practice it usually is (if you're not doing anything else on your main thread...). However, it's perfectly reasonable for updating a display... just don't use the callback to calculate your timer. Save the current time when you start your timer, and get the difference between now and when you started every time the timer fires. Then it doesn't really matter how accurately NSTimer is firing, it only impacts how many times a second your on screen display updates.

Related

Time elapsed when battery increased of 5%

I would like to know if there's a way to get the time elapsed when the battery increased of 5%. For example, how can I know how much time elapsed between 60% and 65% ? I think I could do this with NSTimer, but I'm not able to do this, can someone help me ?
Thanks a lot.
If you are doing this for a Mac, please check this question for how to get battery life in Mac;
If you are doing this for iOS, please check this question for how to get battery life in iOS.
Simply use your NSTimer to fire the function to get the battery life every x seconds and when it gets to 60%, capture a timestamp with NSDate, then when it gets to 65%, capture another timestamp and compare the two timestamps to get the time difference: SO question: how to get time between 2 NSDate objects.
Good luck.
EDIT:
All the methods to get the battery percentage are in either the first or second link based on your platform. If you want it to determine the time between now, and 5% up/down:
//both percent and date should be properties or instance variables (NSDate and float, respectively)
//You should probably also make the timer one as well, so you can stop it in any method with [tmr invalidate];
date = [NSDate date];
percent = [self getBatteryPercent];
NSTimer* tmr = [NSTimer scheduledTimerWithInterval:1 target:self selector:#selector(someMethod) userInfo:nil repeats:YES];
- (float)getBatteryPercent
{
//You'll have to get this code from one of those methods (first or second link)
}
- (void)someMethod
{
float newPercent = [self getBatteryPercent];
if(percent - newPercent == 5.0 || percent - newPercent == -5.0)
{
//Get the time between timestamps
NSDate* newDate = [NSDate date];
//See third link for how to get the time difference between date and newDate
}
}
The rest is up to you.

How to access the remaining time of a non repeating NSTimer

I'm trying to access the remaining time of an NSTimer X. I want to update the title of a button every second to reflect remaining mm:ss until zero. I couldn't find anything here.
For example: [btY setTitle:[What to insert here?] forState:UIControlStateSelected];
Or would you rather solve this in a different way?
You can use fireDate
NSTimer *timer = [NSTimer timerWithInterval:1.0 target:self selector:#selector(updateButton) userInfo:nil repeats:YES];
- (void)updateButton:(NSTimer*)timer
{
float timeRemaining = timer.fireDate.timeIntervalSinceNow;
// Format timeRemaining into your preferred string form and
// update the button text
}
This is generally not how you would solve this.
Create a repeating NSTimer set to the resolution at which you want to update the button instead.
So for instance, if you want your button to change every second until zero, create a NSTimer like so:
NSTimer *timer = [NSTimer timerWithInterval:1.0 target:self selector:#selector(updateButton) userInfo:nil repeats:YES];
Then implement updateButton; basically have a counter for remaining seconds, and every time updateButton gets called, decrease the counter by one, and update the title of the button.
You will not be able to get this kind of information, instead you will need to run the timer several times, for example, if you want to update the button with a text one time each 30 seconds, instead of starting a timer with 30 seconds start a timer with 1 sec and repeat it 30 times

NSTimer Count Up

I am trying to create an NSTimer that counts up from 00:00:00 to whenever the user presses stop. I have created an NSDateInterval of 1 second, but I can't get it to count up from 00:00:00, only the current date or a date that I set.
What is the best way to do this? And is NSTimer the best way to do this or should I just get the difference between the time the user presses the first button ([NSDate date] to set it) and the time at that second (a selector fired off by NSTimer)? I want to make sure there is as little accuracy fault as possible, and I am aware of NSTimer's problems with accuracy sometimes.
Save the time the timer starts with [NSDate date], and then record the time it stops as well. The display time will be the difference, displayed as you listed. The NSTimer will be used just to trigger an update, and you can set the interval fairly small, say 1/10th of a second. Something like:
[NSTimer scheduledTimerWithTimeInterval: 0.1f target: self
selector: #selector(updateTimeDisplay) userInfo: nil repeats: YES];

NSString alloc or not!

I am running this code from the scrollViewDidScroll method (so it runs when you scroll!):
NSString *yearCount = [[NSString alloc] initWithFormat:#"%0.1f", theScroller.contentOffset.y];
years.text = yearCount;
[yearCount release];
which works fine, however it hits performance on the scroll (causing it to judder as it slows down)
My question is, do I need to keep using alloc and release or is there a way to get some numbers using initWithFormat onto some text without it?
years.text = [NSString stringWithFormat:#"%0.1f", theScroller.contentOffset.y];
will avoid the need to explicitly release the string, since it is autoreleased.
However, if you are trying to avoid slowdown, consider updating the field less frequently. For example, each time scrollViewDidScroll is called, set a timer to update the field in say 0.1 seconds from now, but not if the timer is already running from a previous call. This reduces the number of calls while keeping the UI updated.
Here is an example how you could do it. Declare an NSTimer in the interface declaration of your scroll view delegate:
NSTimer *timer;
And methods:
- (void)updateYear:(NSTimer*)theTimer
{
timer=nil;
UIScrollView *theScroller=[theTimer userInfo];
years.text=[NSString stringWithFormat:#"%0.1f", theScroller.contentOffset.y];
}
- (void)scrollViewDidScroll:(UIScrollView *)theScroller
{
if (!timer) {
timer=[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:#selector(updateYear:) userInfo:theScroller repeats:NO];
}
}
Obviously, you don't have to use 0.1 as the time interval, you can try making it faster or slower and see what works best.
Note that this example is complete as far as memory management is concerned, You should not try to retain or release the timer object yourself. Its lifetime is handled internally by the runloop.
Consider using scrollViewDidEndDecelerating method to avoid the frequent updates. Alloc-init is not responsible for the performance decrease, setting the text frequently is. Unless you really need to change it continuously (in which case solution with a timer might be an option), you should be looking for a different hook method.
You've got poor performance absolutely not because of the string formatting or alloc-release. You can use some shorter form like:
years.text = [NSString stringWithFormat:#"%0.1f", theScroller.contentOffset.y];
which is equivalent to
years.text = [[[NSString alloc] initWithFormat:#"%0.1f", theScroller.contentOffset.y] autorelease];
However this won't help to improve your performance at all.

how can we count the time interval of the animation in cocos2d?

I am doing my program in cocos2d.
I am using NSDate to get the current time of the start of animation. And I know my animation takes 3 seconds. So I can get the time at completion of animation by using NSInterval and using the previous time and animation time. But, if If the animation time interval is not fixed how can I calculate the time interval of the animation and time at the completion of the animation ? I am animating a sprite. Please help how can I make it.
Thank You.
The CCIntervalAction class has a property called elapsed that gives you the number of seconds that have elapsed since the action started as a ccTime. Since the CCAnimate action derives from CCIntervalAction, you should have access to this property.
CCAnimation *myAnimation = [CCAnimation animationWithName:#"my animation" delay:0.1f];
CCAnimate *myAnimateAction = [CCAnimate actionWithAnimation:myAnimation];
[sprite runAction:myAnimateAction];
...
ccTime interval = myAnimateAction.elapsed;