StopWatchメモ

Commons LangにStopWatchなるクラスがあったので試してみる。
名前の通り、StopWatchらしい。


メソッドの実行時間なんかを取得するときは、System.currentTimeMillis()を
使っていたけど、このクラスを使っても同じことができる。


まずは、今までのSystem.currentTimeMillis()を使ってたバージョン。


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);
}
これを、StopWatchにしたもの。

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());
}
こいつの実行結果。

1000
3000
途中経過は1回分しか保持しないみたい。


結局はSystem.currentTimeMillis()を使っちゃう気がするけど、
いつかこいつを使うこともあるはず。
いや、使うと信じたい。