Pareod
Pareod

Reputation: 151

Why do these longs get written as 0's or 1's?

Maybe my brain isn't working today, but I am just trying to calculate method execution time and write the times to a file. For some reason, the long values are being written as 0's and 1's. Here is the relevant code:

public static void main(String[] args) {
        //Reads numbers from file
        Scanner numberReader;
        //Writes execution times to file
        BufferedWriter writer;
        String heading = "Euclid (ms)\t\tPrime Factor (ms)\n";
        //Hold numbers from file
        int num1, num2;
        //Holds execution times
        long startTime, endTime, elapsedTime;

    try {
        //Reads file
        numberReader = new Scanner(new File(args[0]));
        //Opens the file to write to
        writer = new BufferedWriter(new FileWriter("comparison.txt", false));
        writer.write(heading);

        //While there are more numbers to read
        while(numberReader.hasNextInt()) {
            //Read the numbers
            num1 = numberReader.nextInt();
            num2 = numberReader.nextInt();

            System.out.println("Numbers: " + num1 + ", " + num2);

            //Run the first method and calculate execution time
            startTime = System.currentTimeMillis();
            System.out.println("Euclid GCD: " + euclid(num1, num2));
            endTime = System.currentTimeMillis();
            elapsedTime = endTime - startTime;
            //Write execution time to file
            writer.write(elapsedTime + "\n");

            //Run the second method and calculate execution time
            startTime = System.currentTimeMillis();
            System.out.println("Prime Factor GCD: " + primeFactor(num1, num2));
            endTime = System.currentTimeMillis();
            elapsedTime = endTime - startTime;
            //Write execution time to file
            writer.write(elapsedTime + "\n");
        }

        //Close the reader and writer
        numberReader.close();
        writer.close();
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}

Here is a sample output:

Euclid (ms)     Prime Factor (ms)
1
1
0
0
0
0

Any ideas?

Upvotes: 0

Views: 52

Answers (1)

Jim Garrison
Jim Garrison

Reputation: 86774

The execution of the methods you are trying to measure is on the order of a few micro-seconds. Those are the times rounded to milliseconds, so any time less than 500µs will output as zero.

You need to use a higher resolution timer such as System.nanoTime(), which can be used to measure shorter intervals, but is useful only for elapsed time, not time of day. I.e. you can subtract two values to get elapsed time but the values themselves do not correlate with any specific time of day.

Note that depending on the hardware you may not get nanosecond resolution, but it will be much better than milliseconds.

Upvotes: 2

Related Questions