- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我编写了一些 java 类,以评估/演示不同的排序算法。但是,当我运行我的演示类(class)时,我感到很困惑。希望大家给我一个解释。 (这道题不是作业。)
首先我会列出一些与这个问题相关的代码。
抽象演示
public abstract class AbstractDemo {
protected final int BIG_ARRAY_SIZE = 20000;
protected final int SMALL_ARRAY_SIZE = 14;
protected Stopwatch stopwatch = new Stopwatch();
public final void doDemo() {
prepareDemo();
specificDemo();
}
protected abstract void prepareDemo();
protected abstract void specificDemo();
protected final void printInfo(final String text) {
System.out.println(text);
}
}
排序演示
public class SortingDemo extends AbstractDemo {
private static final String FMT = "%-10s| %-21s| %7s ms.";
private static final String SPL = AlgUtil.lineSeparator('-', 45);
private static final String SPLT = AlgUtil.lineSeparator('=', 45);
private int[] data;
private final List<Sorting> demoList = new LinkedList<Sorting>();
@Override
protected void specificDemo() {
int[] testData;
//*** this comment is interesting!!! for (int x = 1; x < 6; x++) {
printInfo(String.format("Sorting %7s elements", data.length));
printInfo(SPLT);
for (final Sorting sort : demoList) {
// here I made a copy of the original Array, avoid to sort an already sorted array.
testData = new int[data.length];
System.arraycopy(data, 0, testData, 0, data.length);
stopwatch.start();
// sort
sort.sort(testData);
stopwatch.stop();
printInfo(String.format(FMT, sort.getBigO(), sort.getClass().getSimpleName(), stopwatch.read()));
printInfo(SPL);
testData = null;
stopwatch.reset();
}
//}
}
@Override
protected void prepareDemo() {
data = AlgUtil.getRandomIntArray(BIG_ARRAY_SIZE, BIG_ARRAY_SIZE * 5, false);
demoList.add(new InsertionSort());
demoList.add(new SelectionSort());
demoList.add(new BubbleSort());
demoList.add(new MergeSort()); //here is interesting too
demoList.add(new OptimizedMergeSort());
}
public static void main(final String[] args) {
final AbstractDemo sortingDemo = new SortingDemo();
sortingDemo.doDemo();
}
}
秒表
public class Stopwatch {
private boolean running;
private long startTime;
private long elapsedMillisec;
public void start() {
if (!running) {
this.startTime = System.currentTimeMillis();
running = true;
} else {
throw new IllegalStateException("the stopwatch is already running");
}
}
public void stop() {
if (running) {
elapsedMillisec = System.currentTimeMillis() - startTime;
running = false;
} else {
throw new IllegalStateException("the stopwatch is not running");
}
}
public void reset() {
elapsedMillisec = 0;
}
public long read() {
if (running) {
elapsedMillisec = System.currentTimeMillis() - startTime;
}
return this.elapsedMillisec;
}
}
生成随机数组的方法
public static int[] getRandomIntArray(final int len, final int max, boolean allowNegative) {
final int[] intArray = new int[len];
final Random rand = new Random();
rand.setSeed(20100102);
if (!allowNegative) {
if (max <= 0) {
throw new IllegalArgumentException("max must be possitive if allowNegative false");
}
for (int i = 0; i < intArray.length; i++) {
intArray[i] = rand.nextInt(max);
}
} else {
int n;
int i = 0;
while (i < len) {
n = rand.nextInt();
if (n < max) {
intArray[i] = n;
i++;
}
}
}
return intArray;
}
你可以看到,我生成了一个int数组,有20000个元素。因为我在 getRandomIntArray 方法中有一个固定的种子,所以每次调用它时我总是有相同的数组。 SortingDemo 类有 main 方法,如果我运行这个类,我得到输出:
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 101 ms.
---------------------------------------------
O(n^2) | SelectionSort | 667 ms.
---------------------------------------------
O(n^2) | BubbleSort | 1320 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 39 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 11 ms.
---------------------------------------------
看起来不错。现在出现了让我困惑的事情。如果我更改 SortingDemo 中的 demoList.add() 序列,请说:
demoList.add(new InsertionSort());
demoList.add(new SelectionSort());
demoList.add(new BubbleSort());
// OptimizedMergeSort before Mergesort
demoList.add(new OptimizedMergeSort());
demoList.add(new MergeSort());
我得到了:
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 103 ms.
---------------------------------------------
O(n^2) | SelectionSort | 676 ms.
---------------------------------------------
O(n^2) | BubbleSort | 1313 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 41 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 14 ms.
---------------------------------------------
为什么输出与第一次运行不同? OptimizedMergeSort 比普通 MergeSort 花费的时间更长...
如果我取消注释 for (int x=1; x<6; x++)
SortingDemo 中的行,(使用相同的数组运行测试 5 次)我得到:
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 101 ms.
---------------------------------------------
O(n^2) | SelectionSort | 668 ms.
---------------------------------------------
O(n^2) | BubbleSort | 1311 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 37 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 10 ms.
---------------------------------------------
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 94 ms.
---------------------------------------------
O(n^2) | SelectionSort | 665 ms.
---------------------------------------------
O(n^2) | BubbleSort | 1308 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 5 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 7 ms.
---------------------------------------------
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 116 ms.
---------------------------------------------
O(n^2) | SelectionSort | 318 ms.
---------------------------------------------
O(n^2) | BubbleSort | 969 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 5 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 10 ms.
---------------------------------------------
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 116 ms.
---------------------------------------------
O(n^2) | SelectionSort | 319 ms.
---------------------------------------------
O(n^2) | BubbleSort | 964 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 5 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 5 ms.
---------------------------------------------
Sorting 20000 elements
=============================================
O(n^2) | InsertionSort | 116 ms.
---------------------------------------------
O(n^2) | SelectionSort | 320 ms.
---------------------------------------------
O(n^2) | BubbleSort | 963 ms.
---------------------------------------------
O(?) | OptimizedMergeSort | 4 ms.
---------------------------------------------
O(nlog(n))| MergeSort | 6 ms.
---------------------------------------------
对于其他排序,结果看起来合理。但是对于 mergeSort,为什么第一次运行比后来运行的时间长得多? OptimizedMergeSort 为 37 毫秒:4 毫秒。
我认为即使 Optimized/MergeSort 的实现是错误的,输出应该保持不变,为什么有时相同的方法调用花费的时间更长,有时时间更短?
作为信息,所有这些 *Sort 类都扩展了一个超抽象类 Sorting。它有一个抽象方法 void sort(int[] data)
MergeSort 有 mergeSorting
方法和 merge() 方法。OptimizedMergeSort 扩展了 MergeSort,并覆盖了 mergeSorting()
方法,(因为当数组大小 <= 7 时,它将执行插入排序)并重用 merge()
方法来自 MergeSort
类。
感谢您阅读这么长的文本和代码。如果你们能给我一些解释,我将不胜感激。
所有测试均在 linux 下的 Eclipse 中完成。
最佳答案
微基准测试 Java 代码是出了名的棘手。
即时编译器很可能会在某个时候启动,将您的 Java 字节码编译成 native 机器码。每次编译都需要时间,但生成的代码可能运行得更快。
还有其他陷阱,但我认为上述情况最有可能发生。
以下 SO 答案非常适合阅读:https://stackoverflow.com/a/513259/367273
关于java - 同样的代码,同样的输入,有时跑得快,有时跑得慢,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8369468/
自己试试看: import pandas as pd s=pd.Series(xrange(5000000)) %timeit s.loc[[0]] # You need pandas 0.15.1
我最近开始使用 Delphi 中的 DataSnap 来生成 RESTful Web 服务。在遵循 Marco Cantu 本人和互联网上其他几个人的指导后,我成功地使整个“链条”正常工作。 但是有一
我一直在为操作系统类(class)编写以下代码,但结果有些奇怪。该代码创建x线程并同时运行它们,以便将两个平方矩阵相乘。每个线程将输入矩阵的Number_of_rows/Number_of_threa
我正在尝试确定何时使用 parallel包以加快运行某些分析所需的时间。我需要做的一件事是创建矩阵,比较具有不同行数的两个数据框中的变量。我在 StackOverflow 上问了一个关于有效方法的问题
我最近对我的代码进行了一些清理,并在此过程中更改了此内容(不完全是真实的代码): read = act readSTRef test1 term i var = do t v^!terms.
我正在计时查询和同一个查询的执行时间,分页。 foreach (var x in productSource.OrderBy(p => p.AdminDisplayName) .Wher
我正在开发一个项目 (WPF),我有一个 Datagrid 从数据库加载超过 5000 条记录,所以我使用 BackgroundWorker 来通知用户数据正在加载,但它太慢了,我需要等待将近 2分钟
我在查询中添加 ORDER BY 时遇到问题。没有 ORDER BY 查询大约需要 26ms,一旦我添加 ORDER BY,它大约需要 20s。 我尝试了几种不同的方法,但似乎可以减少时间。 尝试 F
我是 Android 开发新手,遇到了性能问题。当我的 GridView 有太多项目时,它会变得有点慢。有什么方法可以让它运行得更快一些吗? 这是我使用的代码: 适配器: public class C
这里的要点是: 1.设置query_cache_type = 0;重置查询缓存; 2.在 heidisql(或任何其他客户端 UI)中运行任何查询 --> 执行,例如 45 毫秒 3.使用以下代码运行
想象下表: CREATE TABLE drops( id BIGSERIAL PRIMARY KEY, loc VARCHAR(5) NOT NULL, tag INT NOT
我的表 test_table 中的示例数据: date symbol value created_time 2010-01-09 symbol1
首先,如果已经有人问过这个问题,我深表歉意,至少我找不到任何东西。 无论如何,我将每 5 分钟运行一次 cron 任务。该脚本加载 79 个外部页面,而每个页面包含大约 200 个我需要在数据库中检查
我有下面的 SQL 代码,它来自 MySQL 数据库。现在它给了我期望的结果,但是查询很慢,我想我应该在进一步之前加快这个查询的速度。 表agentstatusinformation有: PKEY(主
我需要获取一个对象在 Core Data 中数千个其他对象之间的排名。现在,这是我的代码: - (void)rankMethod { //Fetch all objects NSFet
我正在编写一个应用程序,我需要在其中读取用户的地址簿并显示他所有联系人的列表。我正在测试的 iPhone 有大约 100 个联系人,加载联系人确实需要很多时间。 ABAddressBookRef ad
我正在使用 javascript 将 160 行添加到包含 10 列的表格中。如果我这样做: var cellText = document.createTextNode(value); cell.a
我是 Swift 的新手,我已经设置了一个 tableView,它从 JSON 提要中提取数据并将其加载到表中。 表格加载正常,但是当表格中有超过 10 个单元格时,它会变得缓慢且有些滞后,特别是它到
我在 InitializeCulture 和 Page_PreInit 事件之间的 asp.net 页面中遇到性能问题。当我重写 DeterminePostBackMode() 时,我发现问题出在 b
我在 Hetzner 上有一个带有 256GB RAM 6 个 CPU(12 个线程) 的专用服务器,它位于德国。我有 CENTOS 7.5。 EA4。 我的问题是 SSL。每天大约 2 小时,我们在
我是一名优秀的程序员,十分优秀!