这个问题与基准无关。
我有一个java线程周期,应该在接近周期时间T操作:
public class MyRunnable implements Runnable {
private final long period = 10000L; //period T, in this case 10 secs
public void run() {
while() {
long startTime = this.getTime();
this.doStuff();
long endTime = this.getTime();
long executionTime = endTime - startTime;
if(executionTime < this.period) {
long sleepTime = (this.period - executionTime);
try {
Thread.sleep(sleepTime);
} catch(InterruptedException iex) {/*handle iex*/}
}
}
}
private long getTime() {
return System.currentTimeMillis();
}
private void doStuff() {/*do stuff*/}
}
当然,根据日程安排选择,Thread.sleep(sleepTime)
可能略大于sleepTime
。但是,平均而言,这种方法提供了与周期T的近似平均近似值。
问题
方法:
private long getTime() {
return System.currentTimeMillis();
}
提供挂钟参考时间。如果机器的时钟向前或向后变化,则此实现无法提供T期间的近似值。例如:
long t1 = getTime();
Thread.sleep(30000);
long t2 = getTime();
System.out.println(t2 - t1);
如果有人在Thread.sleep(30000)
“运行”前三分钟手动更改时钟,则会打印204283之类的内容。
由于使用System.currentTimeMillis()
的系统时钟总是在变化(时间服务器同步,系统负载,用户设置等等),因此不能满足我的需求。
解决方案失败
为了提供更强大的时间参考,我尝试了以下getTime方法的实现:
long getTime() {
long result;
ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
if (mxBean.isThreadCpuTimeSupported()) {
result = mxBean.getCurrentThreadCpuTime()/1000000L;
} else {
throw new RuntimeException("unsupported thread cpu time");
}
return result;
}
getCurrentThreadCpuTime
的问题是得到的时间量是线程消耗的CPU时间,而不是该时刻剩余的时间。线程处于休眠状态或被阻止时的剩余时间未考虑在内。例如:
long t1 = getTime();
Thread.sleep(30000);
long t2 = getTime();
System.out.println(t2 - t1);
令人惊讶的是,getCurrentThreadCpuTime
getTime的实现打印出“0”(零)。
我想要的是
我想我需要的是这样的:
private long getTime() {
long cpuCycles = getAmountOfCPUCyclesSinceTheProgramStarted();
long cpuFrequency = getCPUFrequency();
long result = cpuCycles / cpuFrequency;
return result;
}
问题是我没有找到一种以跨平台方式实现getAmountOfCPUCyclesSinceTheProgramStarted()
和getCPUFrequency()
的java方法。
最后,我的问题是:如何以可靠和跨平台的方式获取java中方法的花费时间?