Last active
November 27, 2018 09:32
-
-
Save sunzcdev/9a4c852ff856b6dbe90d390302a03866 to your computer and use it in GitHub Desktop.
统计代码执行时间
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class RunTimer { | |
public static void main(String[] args) { | |
RunTimer timer = new RunTimer("Tag"); | |
try { | |
Thread.sleep(1000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
timer.addSplit("休眠一秒后"); | |
try { | |
Thread.sleep(2000); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
timer.addSplit("休眠两秒后"); | |
timer.dumpToLog(); | |
} | |
private String mTag; | |
private ArrayList<Long> mSplits; | |
private ArrayList<String> mSplitLabels; | |
public RunTimer(String tag) { | |
reset(tag); | |
} | |
public void reset(String tag) { | |
mTag = tag; | |
reset(); | |
} | |
public void reset() { | |
if (mSplits == null) { | |
mSplits = new ArrayList<>(); | |
mSplitLabels = new ArrayList<>(); | |
} else { | |
mSplits.clear(); | |
mSplitLabels.clear(); | |
} | |
addSplit(null); | |
} | |
public void addSplit(String splitLabel) { | |
long now = System.currentTimeMillis(); | |
mSplits.add(now); | |
mSplitLabels.add(splitLabel); | |
} | |
public void dumpToLog() { | |
System.out.println(mTag + ":\t" + "开始计时"); | |
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); | |
System.out.printf("%s:\t%s耗时:\t%d ms \n", mTag, splitLabel, now - prev); | |
} | |
System.out.println(mTag + ":\t" + "总计耗时:\t" + (now - first) + " ms"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment