[英]Java Thread getting elapsed time :: how to get small change
Here is my run for method for thread 这是我的线程方法运行
public void run() {
float timeElapsed =0;
while(running){
time += timeElapsed; // recording time.
if(timeElapsed != 0 )Log.d(id, "pressed time " + time + " "+ timeElapsed);
/**fromhere :: just how I get fps ratio.
oneSec += timeElapsed;
fpsCompound++;
if(oneSec > 1){
fpsCompound = 0;
oneSec = 0;
}
**/endhere
timeBefore = System.nanoTime();
loopCall(timeElapsed);
timeElapsed =(System.nanoTime()-timeBefore)/1000000000;
//sometimes my timeElapsed is 0, my guess is because the loopCall does nothing in some cases
while(timeElapsed < .005){
timeElapsed =(System.nanoTime()-timeBefore)/1000000000;
}
}
}
I want to get rid of that while loop that delays the loop if timeElapsed is less than .005. 如果timeElapsed小于.005,我想摆脱循环延迟循环。
However if I skip that delay portion, I sometimes get my timeElapsed as 0 even though there has to be a tiny portion of seconds passed. 但是,如果我跳过那个延迟部分,我有时会将我的时间缩短为0,即使必须经过一小部分秒。
Accumulated result of these zero elapsed time results in unexpected time error. 这些零经过时间的累计结果导致意外的时间误差。 So I delay my thread if each loop is too fast to record the time.
所以如果每个循环都太快而无法记录时间,我会延迟我的线程。
This unnecessary delay seems pretty stupid. 这种不必要的延迟似乎很愚蠢。 There must be a correct way to calculate the time.
必须有一个正确的方法来计算时间。
EDIT: 编辑:
It seems that dividing timeElapsed by 1000000000 returns value that's too small for my float to contain. 似乎将timeElapsed除以1000000000返回的值对于我的float来说太小了。 Is there a way to contain such a small number?
有没有办法包含这么少的数字?
I think you should keep nanoseconds as long and not convert it into float seconds. 我认为你应该保持纳秒长度,而不是将其转换为浮动秒。
then you'll have code like this: timeElapsed is defined as long: 然后你会得到这样的代码:timeElapsed被定义为long:
long timeElapsed = 0;
End of your loop will look like this: 循环结束将如下所示:
timeBefore = System.nanoTime();
loopCall(timeElapsed);
timeElapsed =(System.nanoTime()-timeBefore);
while(timeElapsed < 5000000){
timeElapsed = (System.nanoTime()-timeBefore);
}
I hope that's what you're looking for. 我希望这就是你要找的东西。
Also I'd recommend to do waiting with Thread.sleep(long, int); 另外我建议等待Thread.sleep(long,int); You'll lose some precision (it sleeps for milliseconds) but will save some CPU time
你将失去一些精度(它睡眠毫秒),但会节省一些CPU时间
/*while(timeElapsed < 5000000){
timeElapsed = (System.nanoTime()-timeBefore);
}*/
long leftToSleep = 5000000 - timeElapsed;
if(leftToSleep > 0) {
//dont forget to surround it with try catch
Thread.sleep(leftToSleep / 1000000, (int) leftToSleep % 1000000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.