silveira neto

carbon-based lifeform. virgo supercluster

Menu Close

Simple Java Chronometer

A very simple Java chronometer code (inspired in the chronometer code in Opale project) you can use for simples measures.

In the main method there’s a example of use.

public final class Chronometer{
    private long begin, end;
 
    public void start(){
        begin = System.currentTimeMillis();
    }
 
    public void stop(){
        end = System.currentTimeMillis();
    }
 
    public long getTime() {
        return end-begin;
    }
 
    public long getMilliseconds() {
        return end-begin;
    }
 
    public double getSeconds() {
        return (end - begin) / 1000.0;
    }
 
    public double getMinutes() {
        return (end - begin) / 60000.0;
    }
 
    public double getHours() {
        return (end - begin) / 3600000.0;
    }
 
    public static void main(String[] arg) {
        Chronometer ch = new Chronometer();
 
        ch.start();
        for (int i = 1;i<10000000;i++) {}
        ch.stop();
        System.out.println(ch.getTime());
 
        ch.start();
        for (int i = 10000000;i>0;i--) {}
        ch.stop();
        System.out.println(ch.getTime());
    }
}

Compiling and running this code gives you something like:

191
12

Maybe you got surprised with this. The first loop, with 10 millions of steps is slower than the second, also with 10 millions of steps.

Why?

Some processors (like x86) have an zero-flag in their ALU. Using it is faster perform the question i≠0 than i<K (for a K≠0). In a loop with 10 millions iterations this difference can be perceptible. And this is not just for Java. You can try those loops in others language and see this behavior.

Think twice next time you write a big loop. :)

© 2016 silveira neto. All rights reserved.

Theme by Anders Norén.