How long does one second take in Java? Measure latency in Java

I do not want to change this code, I am only interested in JVM, OS or kernel / configuration settings for best results!


I have one second loop (1000 x 1 ms)

public static void main(String[] args) throws InterruptedException {
    long start = System.nanoTime();
    for (int i = 0; i < 1000; i++ ) {
        Thread.sleep(TimeUnit.MILLISECONDS.toMillis(1));
    }
    long duration = System.nanoTime()  - start;
    System.out.println("Loop duration " + 
         duration / TimeUnit.MILLISECONDS.toNanos(1) + " ms.");
}

On my Fedora 20 with a 3.12 kernel, this loop takes 1055 ms.

This is a pretty good result, the average value is more than 1100 ms .

Is it possible to make this code faster using custom JVM flags or OS configuration?

Loop duration 1055 ms.
+4
source share
8 answers

Unfortunately, my question was misunderstood.

Java- , Java- Realtime .

Windows.

Windows 8.1 1000 .

:

  • Mac Os X 10.9.1 Java 1.7.0_25: 1180 - 1190ms
  • Ubuntu 12.04/Corei3/4GB: 1122

0

sleep(), . , , . , sleep .

EDIT: , ( ) ! JAva hotspots ( fromm Hotspot JIT), . server VM 10k . 1k.

+14

, - . for, . , , .

-, , , ( "" ) . , , ( " " ), ( ), , . , ( ), , . , "" , .

, : . ; , . , , , , . IDE, , , .

+6
+2

, ( , 200 , 100 1000 forRT-). , 55 . , sleep , .

+1

System.currentTimeMillis . System.nanoTime. .

+1

, , , TimeUnit . , ; != 0 , .

, JITted ( ), .

, Java, , , , . . , , , , , ( ). , . , , , . , . .

, -, 1% , , 1% - . , . Jots Jots, , , , .

+1

?

Thread.sleep(1000);

1000 , :

public static void main(String[] args) throws InterruptedException {

    // This line is for timing reasons only!
    long start = System.currentTimeMillis();

    final long startTime = System.currentTimeMillis();
    long waitTime;

    for (int i = 0; i < 1000; i++ ) {
        // Get the time you want to end with. Then substact your current system time!
        waitTime = (startTime + i + 1)- System.currentTimeMillis();

        // Only wait if it would wait (If waitTime is greater than 0.
        // Everything below 0 will also throw a execption!
        if(waitTime > 0)
            Thread.sleep(waitTime);
    }

    // Same for those...
    long duration = System.currentTimeMillis() - start;
    System.out.println("Loop duration " + duration + " ms.");

}

, !

0

All Articles