[英]System.nanotime giving negative numbers
I writing an android timer app that uses System.nanotime. 我写了一个使用System.nanotime的android定时器应用程序。 The issue is that it's giving me underpredicted results as well negative numbers.
问题是它给了我低估的结果以及负数。 redVal, blueVal, and greenVal are updated on each frame of the camera.
redVal,blueVal和greenVal在相机的每一帧上都会更新。
results 结果
504455566
-95947265
9063721
61035
-99487305
-98937988
12664795
-75317382
code 码
for (testAmount = 0; testAmount < 80; testAmount++) {
runOnUiThread(new Runnable() {
public void run() {
lagSquare.setBackgroundColor(Color.rgb(255, 255, 255));
lagStartTime = System.nanoTime(); //start lagTimer start
}
});
while (redVal <= 100.0 && blueVal <= 100.0 && greenVal <= 100.0) {
x=0;
}
runOnUiThread(new Runnable() {
public void run() {
lagEndTime = System.nanoTime(); //start lagTimer end
lagSquare.setBackgroundColor(Color.rgb(000, 000, 000));//set lagSquare black
}
});
lagTimeResult = (lagEndTime - lagStartTime);
timeArray[testAmount] = lagTimeResult;
Log.i("LTR", String.valueOf(lagTimeResult));
try {
Thread.sleep(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
You are trying to output a time difference which is relying upon values being set in different threads, without any synchronization. 您试图输出时差,该时差依赖于在不同线程中设置的值,而没有任何同步。 This will almost always end up with the wrong value:
这几乎总是会导致错误的值:
for (testAmount = 0; testAmount < 80; testAmount++) {
// this will schedule the Runnable to run *sometime* in
// the future - but not necessarily right now
runOnUiThread(new Runnable() {
public void run() {
lagStartTime = System.nanoTime(); //start lagTimer start
}
});
// this will also schedule this Runnable to run *sometime* in
// the future - but not necessarily after the first one
runOnUiThread(new Runnable() {
public void run() {
lagEndTime = System.nanoTime(); //start lagTimer end
}
});
// this will probably execute first (before either of
// the other Runnables have completed)
lagTimeResult = (lagEndTime - lagStartTime);
}
You simply can't rely on the order of threads executing in the order you've coded them - and definitely not in a loop. 您根本不能依赖于按照对它们进行编码的顺序来执行线程的顺序-绝对不是循环的。 I can't understand from your question what you are trying to time, but the take-home rule is that whenever you have multiple threads, you can never rely on the order of execution without using some form of synchronization.
从您的问题中我无法理解您要尝试计时的时间,但扎根的规则是,只要您有多个线程,就永远不能依靠执行顺序而不使用某种形式的同步。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.