How to accurately calculate the time it takes for a Java program to write or read a file?

How to accurately calculate the time it takes for a Java program to write or read several bytes from / to a file?

It is very important that time is measured accurately. (The time must be calculated by the program itself).

+5
source share
5 answers

Standard idiom:

long startTime = System.nanoTime();
doSomething();
long elapsedTime = System.nanoTime() - startTime;
+16
source

not verified, but something like:

long delta = System.nanoTime();
try {
    // do your stuff
} finally {
    delta = System.nanoTime() - delta;
}
+5
source

:

http://www.goldb.org/stopwatchjava.html

/*
    Copyright (c) 2005, Corey Goldberg

    StopWatch.java is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
*/


public class StopWatch {

    private long startTime = 0;
    private long stopTime = 0;
    private boolean running = false;


    public void start() {
        this.startTime = System.currentTimeMillis();
        this.running = true;
    }


    public void stop() {
        this.stopTime = System.currentTimeMillis();
        this.running = false;
    }


    //elaspsed time in milliseconds
    public long getElapsedTime() {
        long elapsed;
        if (running) {
             elapsed = (System.currentTimeMillis() - startTime);
        }
        else {
            elapsed = (stopTime - startTime);
        }
        return elapsed;
    }


    //elaspsed time in seconds
    public long getElapsedTimeSecs() {
        long elapsed;
        if (running) {
            elapsed = ((System.currentTimeMillis() - startTime) / 1000);
        }
        else {
            elapsed = ((stopTime - startTime) / 1000);
        }
        return elapsed;
    }




    //sample usage
    public static void main(String[] args) {
        StopWatch s = new StopWatch();
        s.start();
        //code you want to time goes here
        s.stop();
        System.out.println("elapsed time in milliseconds: " + s.getElapsedTime());
    }
}
+2

, , . , 1000 , . 1,000,000 , .

, , , (, 10) , , .

+2

get System.xxx , . "" - .

, -, ( ). , . , . .

+1

All Articles