我在互联网上看到我应该使用 System.nanoTime()
但这对我不起作用 - 它给了我毫秒精度的时间。我只需要我的函数执行前后的微秒,这样我就知道需要多长时间。我使用的是 Windows XP。
基本上,我有这段代码,例如,在 java 链表中执行 100 万到 1000 万次插入。问题是我无法正确测量精度;有时在较小的列表中插入所有内容所需的时间更少。
这是一个例子:
class test
{
public static void main(String args[])
{
for(int k=1000000; k<=10000000; k+=1000000)
{
System.out.println(k);
LinkedList<Integer> aux = new LinkedList<Integer>();
//need something here to see the start time
for(int i=0; i<k; i++)
aux.addFirst(10000);
//need something here to see the end time
//print here the difference between both times
}
}
}
我这样做了很多次 - 每个 k 都有一个外部循环执行 20 次 - 但结果并不好。有时进行 1000 万次插入所需的时间比 100 万次要少,因为我现在使用的没有得到正确的测量时间(System.nanoTime())
编辑 2:是的,我使用的是 Sun JVM。
编辑 3:我可能在代码中做错了什么,我会看看更改它是否符合我的要求。
编辑 4:我的错误,似乎 System.nanoTime() 有效。唷。
最佳答案
我的猜测是,自从 System.nanoTime()
使用“最精确的可用系统计时器”,它显然在您的系统上只有毫秒精度,您无法得到更好的结果。
关于java - 如何在 Java 中以微秒精度测量时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/503877/