0

So, I borrowed a timer approach from this excellent post:

Android timer? How-to?

which was very well-written and well-upchecked. However, I find that it fires approximately every 106-114msec, not the desired 100msec. Does this make sense, or does it seem slow? If I wanted to make this closer to an exact 100msec (I am using it in some places to measure durations), what change should I make?

My code is below

Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {

    @Override
    public void run() {

        TickTimer_Elapsed();
        timerHandler.postDelayed(this, 100);
    }
};

void TickTimer_Start() { timerHandler.postDelayed(timerRunnable, );   }
void TickTimer_Stop()  { timerHandler.removeCallbacks(timerRunnable); }

void TickTimer_Elapsed()
{
    m_FSM.Tick_10Hz(); // actually a bit slower than 10Hz

}
Community
  • 1
  • 1
Chris
  • 629
  • 1
  • 10
  • 28
  • use `postAtTime` instead (or use adaptive "delay" when using `postDelayed`) – pskink May 08 '16 at 06:31
  • @pskink Sounds like they want very precise timings, `postAtTime` doesn't promise that either. – weston May 08 '16 at 09:30
  • "I am using it in some places to measure durations" Sounds like an [XY problem](http://xyproblem.info/). What is the problem you are trying to solve? – weston May 08 '16 at 09:31
  • @weston android is not RTOS so nothing in android promise that either, and yes i agree its most likely an XY problem – pskink May 08 '16 at 09:34
  • @pskink I didn't say it was! it was you who was suggesting `postAtTime` as a solution – weston May 08 '16 at 09:46
  • @weston yes i did it since OP problem is that he is always getting something > 100ms because he doesnt take care how much time is spent in `TickTimer_Elapsed()` – pskink May 08 '16 at 09:49

1 Answers1

1

Timer is overloaded term in English, meaning either a device that measures time (e.g. a stopwatch), or a device that triggers after a time (e.g. egg timer).

In Android, the timer is for the latter only, and it does not promise absolute accuracy.

"I am using it in some places to measure durations"

In real life, to tell how much time has passed, you would not to watch a clock and count the seconds ticking by! You'd get nothing else done in that time. An efficient way would be to look at the clock just twice and subtract the two times. The same is true with computers:

e.g:

long startTimeMs = System.currentTimeMillis();

Later:

long durationMs = System.currentTimeMillis() - startTimeMs;
weston
  • 54,145
  • 21
  • 145
  • 203
  • dont forget about `android.util.TimingLogger` – pskink May 08 '16 at 09:47
  • @pskink That's for logging "A utility class to help log timings splits throughout a method call" but I wouldn't use this for profiling even, I'd just profile the app properly using the IDE – weston May 08 '16 at 09:49