Skip to content

Instantly share code, notes, and snippets.

@chaeMil
Created January 11, 2019 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chaeMil/19d193b37f06bb39adc7820ba47885d8 to your computer and use it in GitHub Desktop.
Save chaeMil/19d193b37f06bb39adc7820ba47885d8 to your computer and use it in GitHub Desktop.
Simple Java / Android Profiler

#Usage

SimpleProfiler testProfiler = new SimpleProfiler("TestProfiler", true);
testProfiler.start();
Thread.sleep(300);
testProfiler.addStep("method A");
Thread.sleep(200);
testProfiler.addStep("method B");
Thread.sleep(700);
testProfiler.addStep("method C");
String result = testProfiler.finish();
System.out.print(result);

#Output

TestProfiler: {
[method A took 301ms]
[method B took 200ms]
[method C took 700ms]
}
TestProfiler took 1202ms to complete
import java.util.ArrayList;
/**
* Created by Michal Mlejnek <chaemil72@gmail.com> on 05/02/2018.
*/
public class SimpleProfiler {
private String name;
private final boolean enabled;
private long beginTimestamp;
private ArrayList<Step> steps = new ArrayList();
private boolean finished;
public SimpleProfiler(String name, boolean enabled) {
this.enabled = enabled;
if (enabled) {
this.name = name;
}
}
public void start() {
this.beginTimestamp = System.currentTimeMillis();
}
public void addStep(String name) {
if (enabled && this.beginTimestamp != 0 && !finished)
steps.add(new Step(System.currentTimeMillis(), name));
}
public String finish() {
if (enabled && this.beginTimestamp != 0) {
finished = true;
StringBuilder result = new StringBuilder(name + ": {\n");
for (int i = 0; i < steps.size(); i++) {
createStepString(result, i);
}
result.append("}\n").append(name).append(" took ")
.append(System.currentTimeMillis() - beginTimestamp)
.append("ms to complete");
return result.toString();
} else {
return "Profiler [" + name + "] not enabled or not started";
}
}
private void createStepString(StringBuilder result, int i) {
Step previousStep = null;
if (i > 0) {
previousStep = steps.get(i - 1);
}
Step step = steps.get(i);
String stepTime;
if (previousStep != null) {
long time = ((step.timestamp - beginTimestamp)
- (previousStep.timestamp - beginTimestamp));
stepTime = "[" + step.name + " took " + time + "ms]";
} else {
long time = (step.timestamp - beginTimestamp);
stepTime = "[" + step.name + " took " + time + "ms]";
}
stepTime += "\n";
result.append(stepTime);
}
public class Step {
private long timestamp;
private String name;
Step(long timestamp, String name) {
this.timestamp = timestamp;
this.name = name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment