Skip to content

Instantly share code, notes, and snippets.

@sergchil
Last active January 31, 2018 07:44
Show Gist options
  • Save sergchil/d2849f568d686aa748b35fbc61bb537a to your computer and use it in GitHub Desktop.
Save sergchil/d2849f568d686aa748b35fbc61bb537a to your computer and use it in GitHub Desktop.
Simple Mathod Profiling util forked from Android's TimingLogger
/**
* Created by sergey on 1/29/18.
*/
import android.os.SystemClock;
import java.util.ArrayList;
public class ProfilingUtil {
private static final String PROFILING = "PROFILING";
private static ProfilingUtil sInstance;
private String mLabel;
private ArrayList<Long> mSplits;
private ArrayList<String> mSplitLabels;
private ProfilingUtil() {
reset("init");
}
public static void start(String label) {
getInstance().reset(label);
}
public static void split(String splitLabel) {
getInstance().addSplit(splitLabel);
}
public static void dump() {
getInstance().dumpToLog();
}
private static ProfilingUtil getInstance() {
if (sInstance == null) {
sInstance = new ProfilingUtil();
}
return sInstance;
}
private void reset(String label) {
mLabel = label;
reset();
}
private void reset() {
if (mSplits == null) {
mSplits = new ArrayList<>();
mSplitLabels = new ArrayList<>();
} else {
mSplits.clear();
mSplitLabels.clear();
}
addSplit(null);
}
private void addSplit(String splitLabel) {
long now = SystemClock.elapsedRealtime();
mSplits.add(now);
mSplitLabels.add(splitLabel);
}
private void dumpToLog() {
Log.d(PROFILING, " ");
Log.d(PROFILING, " ");
Log.d(PROFILING, "=======================================");
Log.d(PROFILING, mLabel + ": begin");
final long first = mSplits.get(0);
long now = first;
for (int i = 1; i < mSplits.size(); i++) {
now = mSplits.get(i);
final String splitLabel = mSplitLabels.get(i);
final long prev = mSplits.get(i - 1);
Log.d(PROFILING, mLabel + ": " + (now - prev) + " ms, " + splitLabel);
}
Log.d(PROFILING, mLabel + ": end, " + (now - first) + " ms");
Log.d(PROFILING, "=======================================");
Log.d(PROFILING, " ");
Log.d(PROFILING, " ");
}
}
@sergchil
Copy link
Author

sergchil commented Jan 31, 2018

USAGE

ProfilingUtil.start("method name");
 // code here...
ProfilingUtil.split("label 1");
// code here...
ProfilingUtil.split("label 2");
// code here...
ProfilingUtil.dump(); // prints the result

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment