karanatwal.github.io
karanatwal.github.io

Reputation: 3673

Handler not running 1000 times in 1 second

I have a task in which i want to update something every millisecond(some kind of calculations). Now here is what i am doing giving 1 millisecond delay.-

 int countertest =0;

 myRunnable = new Runnable() {
                    @Override
                    public void run() {
                        countertest++;
                        System.out.println("----counter----->"+countertest);
                        myHandler.postDelayed(myRunnable, 1); //runs every 1 millisecond
                    }
                };

I start myHandler on click of a button and stop it (removeCallbacksAndMessages(null)) exactly after 1 second. Now myHandler was supposed to run it 1000 times in one second. But it runs sometimes 110 times, sometimes 119 sometimes...some random numbers. Don't know why its not running exactly 1000 times in 1 second. Can anyone elaborate on it please.

What should I do now to execute something exactly 1000 times in 1 second ? Let's say for sake of just example if i want to show text from 0000 to 1000 in one second or print 0-1000 exactly in 1 second, neither more than 1 second nor less. Downvoters pls. comment below so that i can know where i am wrong. Thanks.

Device used for above test - Samsung S9.

Upvotes: 0

Views: 368

Answers (2)

emandt
emandt

Reputation: 2708

Delays cannot respects exactly what we set. For example the "Thread.sleep(1)" could take more than 10ms to be executed. Same things for "postDelayed()" method. The resolution is CPU and current_load depending and all the Docs/Guides warns about this "not absolute exact" time in these cases.

Upvotes: 1

PeterMmm
PeterMmm

Reputation: 24630

As stated here, there is no guarantee for milliseconds accuracy in "your "system at all:

Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

Upvotes: 3

Related Questions