Skip to content

Instantly share code, notes, and snippets.

@pmbanka
Created September 28, 2015 15:16
Show Gist options
  • Save pmbanka/8fd2495cef0bf9677dae to your computer and use it in GitHub Desktop.
Save pmbanka/8fd2495cef0bf9677dae to your computer and use it in GitHub Desktop.
TimeLogger class
package com.foo.bar.baz
import rx.functions.Action0;
import rx.functions.Func0;
import timber.log.Timber;
import java.io.Closeable;
public class TimeLogger implements Closeable
{
private final long startTime;
private final String where;
private final String what;
private int lapIndex;
private long lapStartTime;
private TimeLogger(String where, String what)
{
this.where = where;
this.what = what;
this.startTime = System.nanoTime();
this.lapIndex = 0;
this.lapStartTime = this.startTime;
}
public static <T> T measure(Func0<T> func, String where, String what)
{
try (TimeLogger ignored = new TimeLogger(where, what))
{
return func.call();
}
}
public static void measure(Action0 action, String where, String what)
{
try (TimeLogger ignored = new TimeLogger(where, what))
{
action.call();
}
}
public static TimeLogger start(String where, String what)
{
return new TimeLogger(where, what);
}
public void lapFinished()
{
lapFinished(null);
}
public void lapFinished(String lapName)
{
long nextLapStartTime = System.nanoTime();
long duration = (nextLapStartTime - lapStartTime) / 1000000;
Timber.d("[%s] {%s} lap in {%s} took %d ms", where, lapName != null ? lapName : String.valueOf(lapIndex), what, duration);
lapIndex++;
lapStartTime = nextLapStartTime;
}
@Override
public void close()
{
long endTime = System.nanoTime();
long duration = (endTime - startTime) / 1000000;
Timber.d("[%s] {%s} took %d ms", where, what, duration);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment