Search code examples
javatimedoublemilliseconds

Calculating the average traverse time for a graph in millisecond gives an inconceivable output?


I'm making a performance test about search in graphs (between an adjacency list and adjacency matrix) to calculate average traverse time for whole graph in ms.

However, the output gives a number that I havent seen before. Here is the simple algorithm of test.

   double startTime;
   double endTime;
   double processTime;

   double totalTime = 0;
   double averageTime = 0;

    for (int i = 0; i < 100000; i++) {


        startTime = System.nanoTime();

        search.DFS(5);

        endTime = System.nanoTime();

        processTime = (endTime - startTime)/1000000;

        totalTime = totalTime + processTime;
    }

    averageTime = totalTime/100000;

    System.out.println("PROCESS TIME in AdjacencyMatrix = " + averageTime + " ms");

and the output looks like ;

PROCESS TIME in AdjacencyMatrix = 1.4765902999997995E-4 ms

When I traverse just one time the output gives convenient data like 0.032344 ms.


Solution

  • Even if you use double you still can get precision errors. Basically a floating point number is always a sum of numbers to the power of ten. With that means not all number can be saved precisely. I'm guessing that's where your problem lies.

    As a solution: Use long for your variables which is the return type of System.nanoTime(). The number returned by this is always a whole number.