StopWatchメモ
Commons LangにStopWatchなるクラスがあったので試してみる。
名前の通り、StopWatchらしい。
メソッドの実行時間なんかを取得するときは、System.currentTimeMillis()を
使っていたけど、このクラスを使っても同じことができる。
まずは、今までのSystem.currentTimeMillis()を使ってたバージョン。
これを、StopWatchにしたもの。
public static void main(String[] args) {
long start = System.currentTimeMillis();
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
実行結果。
public static void main(String[] args) {
StopWatch sw = new StopWatch();
sw.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
sw.stop();
System.out.println(sw.getTime());
}
まぁなんてことはない。
1000
ついで。
本物のStopWatchのように、途中経過も取得できる。
こいつの実行結果。
public static void main(String[] args) throws InterruptedException {
StopWatch sw = new StopWatch();
sw.start();
Thread.sleep(1000);
sw.split();
Thread.sleep(2000);
System.out.println(sw.getSplitTime());
sw.stop();
System.out.println(sw.getTime());
}
途中経過は1回分しか保持しないみたい。
1000
3000
結局はSystem.currentTimeMillis()を使っちゃう気がするけど、
いつかこいつを使うこともあるはず。
いや、使うと信じたい。