1

预先感谢您的帮助。我正在开发一个基于 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());
}

该程序报告说,它对我运行的案例的实际工作时间大约是实际工作时间的两倍。

谢谢

4

2 回答 2

4

System.nanoTime() returns time values in nanoseconds. Time() takes a value in milliseconds as a parameter. This would throw your time value off by a factor of 10^-6.

于 2012-06-12T21:58:18.010 回答
1

Time takes milliseconds as a constructor parameter, where as nanoTime() gives you nanoseconds precision, could that be the problem?

discussion here: System.currentTimeMillis vs System.nanoTime

于 2012-06-12T21:58:50.927 回答