如何在Java中以微秒精度测量时间? [英] How can I measure time with microsecond precision in Java?

查看:167
本文介绍了如何在Java中以微秒精度测量时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上看到我应该使用System.nanoTime()但这对我不起作用 - 它给我时间精确到毫秒。我只需要在函数执行之前和之后的微秒,这样我就知道需要多长时间。我正在使用Windows XP。

I saw on the Internet that I was supposed to use System.nanoTime() but that doesn't work for me - it gives me the time with milliseconds precision. I just need the microseconds before and after my function executes so that I know how long it takes. I'm using Windows XP.

基本上,我有这样的代码,例如,在java链表中进行了100万到1000万次插入。问题是我无法测量精确度;有时在较小的列表中插入所有内容所需的时间较短。

Basically, I have this code that, for example, does 1 million up to 10 millions of insertions in a java linked list. The problem is that I can't measure the precision right; sometimes it takes less time to insert everything in the smaller list.

以下是一个示例:

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())

I did this many times - there was an exterior loop doing it 20 times for each k - but the result aren't good. Sometimes it takes less time to to make 10 million insertions than 1 million, because I'm not getting the correct measured time with what I'm using now (System.nanoTime())

编辑2:是的,我正在使用Sun JVM。

Edit 2: Yes, I'm using the Sun JVM.

编辑3:我可能在代码中做错了,我会看看是否改变它做我想要的。

Edit 3: I may have done something wrong in the code, I'll see if changing it does what I want.

编辑4:我的错误,似乎System.nanoTime()工作。 Phew。

Edit 4: My mistake, it seems System.nanoTime() works. Phew.

推荐答案

我猜是因为 System.nanoTime() 使用最精确可用的系统计时器你的系统显然只有毫秒级的精度,你无法获得更好的效果。

My guess is that since System.nanoTime() uses the "most precise available system timer" which apparently only has millisecond-precision on your system, you can't get anything better.

这篇关于如何在Java中以微秒精度测量时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆