【发布时间】:2020-04-16 14:00:59
【问题描述】:
我正在 Eclipse 中使用 Junit5 测试新的插入排序。我已经编写了其他三个测试,它们都通过了,没有错误。我想在test04 中测试的是,插入排序对已排序的int[] 进行排序所花费的时间是否小于对完全向后排序的int[] 进行排序所花费的时间。
这是我的代码:
@Test
void test04() {
// Let's test if sorting an already sorted array takes less time than sorting a backwards one
int[] sorted = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] backwards = {9, 8, 7, 6, 5, 4, 3, 2, 1};
long start = System.currentTimeMillis();
InsertionSort.Sort(sorted);
long sortedTime = System.currentTimeMillis() - start;
start = System.currentTimeMillis();
InsertionSort.Sort(backwards);
long backwardsTime = System.currentTimeMillis() - start;
System.out.println(sortedTime);
System.out.println(backwardsTime);
System.out.println(System.currentTimeMillis());
assert(backwardsTime > sortedTime);
}
问题是我的计时机制(使用System.currentTimeMillis())根本不起作用!这是控制台输出:
0
0
1587044842939
sortedTime 和 backwardsTime 等于 0!所以test04 失败了,因为0 不大于0。有趣的是,当我打印出System.currentTimeMillis() 时,它给了我一个看起来很正常的数字。我想知道怎么了?这是一个错误吗?难道我做错了什么?
欢迎任何帮助!
【问题讨论】:
-
如果它需要 less 然后是一毫秒,您认为值是多少?此外,实际值和准确性取决于您的系统。
-
你认为在任何远程现代的东西上对一个 9 元素数组进行排序需要多长时间?
-
@M.Deinum 我不确定。我怀疑它需要不到一毫秒的时间。
-
像这样测试性能的单元测试对我来说似乎很奇怪。我只想建议另一种选择:让您的排序方法返回比较次数或执行的交换次数。 (或者,提供某种方法来检测代码以获取这些值。)然后,您可以比较方法完成的工作,而不是所花费的时间。
-
@DavidConrad 这是个好主意,很有道理。
标签: java eclipse junit5 insertion-sort