Skip to content

Instantly share code, notes, and snippets.

@gabrielrubens
Created February 20, 2014 17:49
Show Gist options
  • Save gabrielrubens/9119455 to your computer and use it in GitHub Desktop.
Save gabrielrubens/9119455 to your computer and use it in GitHub Desktop.
Medindo o tempo de execução de métodos. Classe de teste.
public class Main {
public static void main(String[] args) throws InterruptedException {
TimerLogger timerLoger = new TimerLogger();
timerLoger.start();
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
timerLoger.partial();
}
timerLoger.end();
System.out.println("---------------------------");
timerLoger.start("classe Main");
for (int i = 0; i < 10; i++) {
Thread.sleep(1000);
timerLoger.partial("um metodo");
}
timerLoger.end("outro lugar");
}
}
/**
* @author Gabriel Rubens - http://gabrielrubens.com.br
* Apenas um teste de tempo de execução de metodos
*/
public class TimerLogger {
private static final String NOW = "Now";
public long timer;
public void start(){
this.start(NOW);
}
public void start(String label){
this.timer = currentTimeMillis();
this.print(formatLabel(label), timer);
}
public void partial(){
this.partial("");
}
public void partial(String label){
long partial = currentTimeMillis();
this.print(formatLabel(label), partial - this.timer);
}
public void end(){
this.end(NOW);
}
public void end(String label){
long end = currentTimeMillis();
this.print("end\t", end - this.timer);
this.print(formatLabel(label), currentTimeMillis());
}
private String formatLabel(String label) {
if(label.isEmpty()) return "";
return label + " - ";
}
private void print(String label, long timerPrint){
int hours = (int) ((timerPrint / (1000*60*60)) % 24);
int minutes = (int) ((timerPrint / (1000*60)) % 60);
int seconds = (int) (timerPrint / 1000) % 60 ;
int milliseconds = (int) (timerPrint / 1000);
System.out.println(String.format("%s%d h, %d min, %d sec, %d mil",
label, hours, minutes, seconds, milliseconds));
}
private long currentTimeMillis() {
return System.currentTimeMillis();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment