Skip to content

Instantly share code, notes, and snippets.

@shawnfeng0
Last active November 8, 2018 18:02
Show Gist options
  • Save shawnfeng0/43723b05fb22ba1ed0f1bf1c6a57ec0d to your computer and use it in GitHub Desktop.
Save shawnfeng0/43723b05fb22ba1ed0f1bf1c6a57ec0d to your computer and use it in GitHub Desktop.
import android.support.annotation.NonNull;
/**
* Measuring code runtime.
* For example:
* long timeSpent = TimeMeasure.doTimeMeasureUs(() -> {
* if (!nativeSendFrame(receiverName, videoBufferByte)) {
* if (++mErrorCount >= ERROR_MAX_COUNT) {
* throw new Exception("Send frame error.");
* }
* }
* });
* Log.d(TAG, "nativeSendFrame: " + TimeMeasure.toString(timeSpent));
*/
class TimeMeasure {
private long startTimeNs;
private long measureResultNs;
private long getMeasureResultNs() {
return measureResultNs;
}
private TimeMeasure start() {
startTimeNs = System.nanoTime();
return this;
}
private TimeMeasure stop() {
measureResultNs = System.nanoTime() - startTimeNs;
return this;
}
@NonNull
@Override
public String toString() {
return toString(measureResultNs);
}
interface Callback {
void measureCode() throws Exception;
}
static long doTimeMeasureUs(Callback callback) throws Exception {
TimeMeasure timeMeasure = new TimeMeasure().start();
callback.measureCode();
return timeMeasure.stop().getMeasureResultNs();
}
static String toString(long timeSpentNs) {
return "time spent " + (timeSpentNs / 1e6) + "ms, " + (timeSpentNs % 1e6) + "ns";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment