我正在努力优化我为圣诞节制作的一个小程序。我正在测试运行这些方法所花费的时间,其中一个,Snow_AI,正在运行1234567纳秒。
问题在于计数器方法:
public boolean Count() {
if (CreateCnt > CreateTime) {
CreateCnt = 0;
return true;
} else {
CreateCnt = CreateCnt + 1;
}
return false;
}
这就是我拨打电话的方式:
MethTmr1 = System.nanoTime();
if (Snw.Count()) {
MethTmr = System.nanoTime();
Snw.Snow_AI();
MethTPS = 1000000000 / (System.nanoTime() - MethTmr);
}
try{
MethTPS1 = 1000000000 / (System.nanoTime() - MethTmr1);
}catch(Exception e){}
当我在If语句中移动计时调用时,它将运行时间改为小于5000.任何人都知道为什么计数器方法会导致这种情况发生?
答案 0 :(得分:1)
您的测量存在缺陷。
请检查:Why is System.nanoTime() way slower (in performance) than System.currentTimeMillis()?
然后看看你的代码:
MethTmr1 = System.nanoTime();
if (Snw.Count()) {
//expensive! Added to outer time
MethTmr = System.nanoTime();
Snw.Snow_AI();
//expensive! Added to outer time
MethTPS = 1000000000 / (System.nanoTime() - MethTmr);
}
try{
MethTPS1 = 1000000000 / (System.nanoTime() - MethTmr1);
}catch(Exception e){}
基线。您的MethTPS1包括您的(快速)getCount(),您的Snow_AI()和两个tcalls到System.nanoTime()
尝试一次:
MethTmr1 = System.nanoTime();
if (Snw.Count()) {
//expensive! Added to outer time
//MethTmr = System.nanoTime();
Snw.Snow_AI();
//expensive! Added to outer time
//MethTPS = 1000000000 / (System.nanoTime() - MethTmr);
}
try{
MethTPS1 = 1000000000 / (System.nanoTime() - MethTmr1);
}catch(Exception e){}