首页 > 解决方案 > 当执行需要很长时间时,nanoTime() 显示的差异太小

问题描述

我正在尝试收集有关执行时间的数据,并比较堆树与 bst 的入队和出队时间。对于经过的时间,我使用 nanoTime()。

在将未排序和已排序的堆树入队/出队时,一切看起来都很好。在排队 bst 时也是如此。当我尝试使用 700000 个元素将排序的 bst 出列时,执行需要很长时间。没关系,在将排序的 bst 排队时也是如此。

问题是执行所用的时间不正确。时间应该是大约 15000 毫秒,但我得到的答案大约是 0.5 毫秒(或 459053 ns)。

首先,我将包含 640000 个元素(整数)的 bst 排入队列,然后对树进行排序。我感兴趣的是排队这个 bst 时的执行时间(已经有 640000 个排序元素)。

这是我的代码(部分):

public static void main(String[] args)
            throws DuplicateItemException, FileNotFoundException, IOException, EmptyQueueException {

        final String pathFullList = "Files/data_640000.txt";
        final String pathPartialList = "Files/data_6400.txt";
        final int SIZE_SEVEN = 640000;
        final int SIZE_FOR_LIST_TWO = 6400;

        BSTPriorityQueue<Integer> bstQueue = new BSTPriorityQueue<Integer>();
        bstQueue.clear();

        List<Integer> listOne = new ArrayList<Integer>();
        listOne = loadList(pathFullList, SIZE_SEVEN);

        Collections.sort(listOne);
        long execTimeForSort = System.nanoTime() - t2;
        System.out.println("Time for sort: " + execTimeForSort);

        enqueueBstTree(listOne, bstQueue);
        System.out.println("Size of hptree before enqueue: " + hPQueue.size() + 
                "\n" + "Size of bsttree before enqueue: " + bstQueue.size());

        List<Integer> listTwo = new ArrayList<Integer>();
        listTwo = loadList(pathPartialList, SIZE_FOR_LIST_TWO);

        long t1 = System.nanoTime();
        dequeueBstTree(listTwo, bstQueue, SIZE_FOR_LIST_TWO);
        long execTime = System.nanoTime() - t1;

        System.out.println("Time difference for enqueue/dequeue: " + execTime);
        System.out.println("Size of hptree after enqueue/dequeue: " + hPQueue.size() + 
                "\n" + "Size of bsttree after enqueue/dequeue: " + bstQueue.size());
    }

执行此代码可能需要 20 分钟。我从 execTime 得到的答案是 459053 纳秒。

标签: java

解决方案


您的System.nanoTime()用法是正确的,但是execTime仅针对dequeueBstTree()方法调用进行测量。如果整个程序执行需要 20 分钟,那么大部分时间都花在了测量的dequeueBstTree()方法调用之外。它可以是任何东西:JVM 启动、堆大小调整、GC 周期、main()...中的其他逻辑

您最可能想要做的dequeueBstTree().


推荐阅读