multithreading - Java Thread getting elapsed time :: how to get small change -


here run method thread

public void run() {     float timeelapsed =0;     while(running){         time += timeelapsed; // recording time.         if(timeelapsed != 0 )log.d(id, "pressed time " + time + " "+ timeelapsed); /**fromhere :: how fps ratio.         onesec += timeelapsed;         fpscompound++;         if(onesec > 1){             fpscompound = 0;             onesec = 0;         } **/endhere          timebefore = system.nanotime();         loopcall(timeelapsed);         timeelapsed =(system.nanotime()-timebefore)/1000000000; //sometimes timeelapsed 0, guess because loopcall nothing in cases         while(timeelapsed < .005){             timeelapsed =(system.nanotime()-timebefore)/1000000000;         }     } } 

i want rid of while loop delays loop if timeelapsed less .005.

however if skip delay portion, timeelapsed 0 though there has tiny portion of seconds passed.

accumulated result of these 0 elapsed time results in unexpected time error. delay thread if each loop fast record time.

this unnecessary delay seems pretty stupid. there must correct way calculate time.

edit:

it seems dividing timeelapsed 1000000000 returns value that's small float contain. there way contain such small number?

i think should keep nanoseconds long , not convert float seconds.

then you'll have code this: timeelapsed defined long:

            long timeelapsed = 0; 

end of loop this:

            timebefore = system.nanotime();             loopcall(timeelapsed);             timeelapsed =(system.nanotime()-timebefore);                     while(timeelapsed < 5000000){                 timeelapsed = (system.nanotime()-timebefore);             } 

i hope that's you're looking for.


also i'd recommend waiting thread.sleep(long, int); you'll lose precision (it sleeps milliseconds) save cpu time

         /*while(timeelapsed < 5000000){               timeelapsed = (system.nanotime()-timebefore);            }*/              long lefttosleep = 5000000 - timeelapsed;            if(lefttosleep > 0) {               //dont forget surround try catch               thread.sleep(lefttosleep / 1000000, (int) lefttosleep % 1000000);            } 

Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -