Skip to content

Tag: clock

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. 🙂

JavaScript: Relógio Digital


Código-Fonte

Aqui na página colocamos:



Que cria um input de texto com nome relógio e depois chamamos o script relogio.js que contém o seguinte código:

function proximo_segundo(){
	var hoje = new Date
	var hora = hoje.getHours()
	var minutos = hoje.getMinutes()
	var segundos = hoje.getSeconds()
	relogio = document.getElementById('relogio')
	relogio.value = hora +":"+minutos+":"+segundos
	setTimeout('proximo_segundo()',1000)
}
proximo_segundo()

Ele cria um objeto Date, encontro o elemento com id ‘relogio’ e coloca no valor dele as informações extraídas do objeto Date. Em seguida ele agenda para daqui a um segundo chamar a si próprio, recursivamente.

Um refinamento que se pode fazer nesse código é uma função auxiliar para preencher com um zero à esquerda, transformando 1:2:3 em 01:02:03. Eu não coloquei isso para deixar o código o mais simples possível.

Como eu ainda sou muito novinho no JavaScript eu não sei se usar uma recursão desse tipo é uma boa idéia ou não. Era isso ou um laço infinito.