与Java System.Time混淆

时间:2012-06-12 21:55:48

标签: java time

提前感谢您的帮助。我正在开发一个基于java的工具,它正在执行一些数据库工作。我有一个非常简单的问题。由于某种原因,报告完成任务的时间不正确。

public static void makeDatabaseThreaded() throws IOException, InterruptedException {        
    final long startTime = System.nanoTime();       

    ArrayList<String> tablesMade = new ArrayList<>();
    File rootDirectory = root;
    String[] files = rootDirectory.list();
    double percentDone = 0;
    double numOfTablesMade = 0;
    double numberOfTables = 62.0;
    DatabaseBuilderThread lastThread = null;
    for (int i = 0; i <= files.length - 1; i++) {

        if (!files[i].contains(".csv")) {
            continue;
        }
        File file = new File(rootDirectory + File.separator + files[i]);

        String tableName = getTableNameFromFile(file);
        if (!tablesMade.contains(tableName)) {
            tablesMade.add(tableName);

            DatabaseBuilderThread thread = new DatabaseBuilderThread(i, file);
            lastThread = thread;
            thread.start();
            threadsRunning++;

            numOfTablesMade++;
            percentDone = (int) (100.0 * (numOfTablesMade) / (numberOfTables));

            while (threadsRunning > 10) {
                Thread.sleep(1000);
            }
            System.out.println(percentDone + "% done. Making Table For File: "  + file.getName());
        }
    }

    //Make Sure all threads are done
    lastThread.join();

    final long endTime = System.nanoTime();
    final long duration = endTime - startTime;
    Time time = new Time(duration);
    System.out.println("Done Making The Database. It took " + time.toString());
}

该计划报告说它的工作时间大约是我运行的案例的两倍。

由于

2 个答案:

答案 0 :(得分:4)

System.nanoTime()以纳秒为单位返回时间值。 Time()以毫秒为单位作为参数。这会使你的时间价值降低10 ^ -6。

答案 1 :(得分:1)

Time需要毫秒作为构造函数参数,其中nanoTime()给出纳秒精度,这可能是问题吗?

在这里讨论:System.currentTimeMillis vs System.nanoTime