java - 当执行需要很长时间时,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 纳秒。
解决方案
您的System.nanoTime()
用法是正确的,但是execTime
仅针对dequeueBstTree()
方法调用进行测量。如果整个程序执行需要 20 分钟,那么大部分时间都花在了测量的dequeueBstTree()
方法调用之外。它可以是任何东西:JVM 启动、堆大小调整、GC 周期、main()
...中的其他逻辑
您最可能想要做的是为dequeueBstTree()
.
推荐阅读
- stripe-payments - 将 GooglePay 与 Stripe 网关结合使用
- python - 使用多个 2d 图像生成 3d 云点
- scala - 计算由窗口函数分区的给定列的不同值,而不使用 approx_count_distinct()
- android-room - Android房间插入/更新结果
- javascript - Vue Bootstrap 加载按钮
- python-3.x - 如何从数据框中的日期列中删除 HH:MM:SS?
- sql - 在 Impala 中查找月份中的第几周
- postgresql - 在 Intellij 中运行 PostgreSQL 存储过程
- vim - Windows 终端应用程序中 Ubuntu 20.04 终端上的 vim 光标位置错误
- amazon-web-services - 将 aws websocket api 与 springboot 应用程序集成