java - 在 Java 中计算耗时时收到 NaN

标签 java binary-search

我正在编写一个程序,使用穷举搜索和二分搜索来搜索英语词典。我必须打印出每个人的平均值。 这是两者的代码。我真的不认为问题在于 find 和 findUsingBinarySearch 本身。

public static double measureAverageExhaustiveSearchTime(String[] queries, String[] array){
    //Measures the average number of microseconds (µs) needed to find each query, using exhaustive search.
    long startTime = System.currentTimeMillis();
    for(int i = 0; i < queries.length; i++){
        find(queries[i], array);
    }
    long endTime = System.currentTimeMillis();
    double elapsedTime = (endTime - startTime);
    return (double)((elapsedTime/1000000000.0)/queries.length);
    }

   public static double measureAverageBinarySearchTime(String[] queries, String[] array){
    //Measures the average number of microseconds (µs) needed to find each query, using binary search.
    long startTime = System.nanoTime();
    for(int i = 0; i < queries.length; i++){
        findUsingBinarySearch(queries[i], array);
    }
    long endTime = System.nanoTime();
    double elapsedTime = (endTime - startTime);
    return (double)((elapsedTime/1000000000.0)/queries.length);

        //(double)(elapsedTime * 1000)/(queries.length);
}

我的输出只是:

详尽的搜索: NaN 秒

二分搜索: NaN 秒

彻底搜索失败: NaN 秒

二进制搜索失败: NaN 秒

<小时/>

当我使用更小的文件时,我得到了这个!

详尽的搜索: 0.0 秒

二分搜索: 2.1E-6秒

彻底搜索失败: 1.0E-10秒

二进制搜索失败: 1.4E-6秒

这是我调用该方法的方式,使用字典作为两个参数,因为我试图测试数组进行二分搜索本身需要多长时间。我还使用了字典的副本,每个单词都附加了“zzz”,以方便失败的二进制和穷举搜索。

    System.out.println("EXHAUSTIVE SEARCH: ");
System.out.println(measureAverageExhaustiveSearchTime(dictionary, dictionary)+" seconds");
System.out.println("BINARY SEARCH: ");
System.out.println(measureAverageBinarySearchTime(dictionary, dictionary)+" seconds");         
System.out.println("FAILED EXHAUSTIVE SEARCH: ");
System.out.println(measureAverageExhaustiveSearchTime(dictionaryzzz, dictionary) + " seconds");
System.out.println("FAILED BINARY SEARCH: ");
System.out.println(measureAverageBinarySearchTime(dictionaryzzz, dictionary)+" seconds");

我不确定如何解决这个问题。

最佳答案

如果您尝试将毫秒转换为微秒,则应该乘以而不是除以 1000。

您的measureAverageExhaustiveSearchTime代码:

return (double)((elapsedTime/1000000000.0)/queries.length);

这应该是:

return (double)((elapsedTime*1000.0)/queries.length);

此外,在求解 elapsedTime 时,我会通过将其转换为 double 来避免转换 startTimeendTime 长数据类型。尝试保留一种数据类型。数据类型转换有时会导致结果被截断或意外的值下限。

关于java - 在 Java 中计算耗时时收到 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20168292/

相关文章:

java - Gradle:无法从 '11.0.2' 确定 java 版本

java - 从文件中读取文本并将其放入 JLabel

algorithm - 哪个搜索更快,二分搜索还是使用前缀树?

python - 如何返回 Python 数组中目标元素的索引?

search - 二分查找或 Btree 索引更新问题

c++ - 为什么会出现段错误以及如何解决它

java - 无法构建 Spring maven 项目,POM.XMl 文件中出现问题

Java - 正在读取的文件返回 null

java - System.lineSeparator() 在 Windows 上未按预期工作

java - 为什么二分查找返回-1