【问题标题】:System.currentTimeMillis not working properly in Junit Test in Eclipse [duplicate]System.currentTimeMillis 在 Eclipse 的 Junit 测试中无法正常工作 [重复]
【发布时间】: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

sortedTimebackwardsTime 等于 0!所以test04 失败了,因为0 不大于0。有趣的是,当我打印出System.currentTimeMillis() 时,它给了我一个看起来很正常的数字。我想知道怎么了?这是一个错误吗?难道我做错了什么?

欢迎任何帮助!

【问题讨论】:

  • 如果它需要 less 然后是一毫秒,您认为值是多少?此外,实际值和准确性取决于您的系统。
  • 你认为在任何远程现代的东西上对一个 9 元素数组进行排序需要多长时间?
  • @M.Deinum 我不确定。我怀疑它需要不到一毫秒的时间。
  • 像这样测试性能的单元测试对我来说似乎很奇怪。我只想建议另一种选择:让您的排序方法返回比较次数或执行的交换次数。 (或者,提供某种方法来检测代码以获取这些值。)然后,您可以比较方法完成的工作,而不是所花费的时间。
  • @DavidConrad 这是个好主意,很有道理。

标签: java eclipse junit5 insertion-sort


【解决方案1】:

两种输入大小都非常小,因此很有可能花费不到 1 毫秒。您可以使用System.nanoTime 以纳秒为单位测量时间。

【讨论】:

  • 不客气。 :-) 仅供参考: 像这样以纳秒精度进行基准测试可能会给您带来错误的结果,因为所有类型的东西都会影响运行时。在如此高的精度下,这会使您的结果变得模糊。您可以通过多次运行测试来检查这一点。值变化很大的可能性很高。您应该查看this 的帖子。
【解决方案2】:

这可能需要不到一毫秒的时间来完成。改用 System.nanoTime 来获得纳秒。

        long start = System.nanoTime();

        InsertionSort.Sort(sorted);

        long sortedTime = System.nano() - start;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-01
    • 2023-02-15
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2010-09-30
    相关资源
    最近更新 更多