18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Java] Google製Stopwatchが便利

Last updated at Posted at 2014-06-27

Javaでプログラムの実行時間を表示したいときにguavaライブラリのStopwatchが便利だという話。
実行時間の表示単位(μs, ms, s, etc.)を自動的に判断して表示してくれる。

コード

import com.google.common.base.Stopwatch;

/**
 * GuavaのStapwatchのデモ
 */
public class StopwatchDemo
{
    public static void main(String[] args) throws InterruptedException
    {
        Stopwatch sw = Stopwatch.createUnstarted();

        long[] millis = {0, 0, 0, 1, 10, 100, 1000, 10000};
        int[] nanos   = {10, 100, 1000, 0, 0, 0, 0, 0};

        for (int i = 0; i < nanos.length; i++) {
            sw.start();
            Thread.sleep(millis[i], nanos[i]);
            System.out.print(String.format("%5dms %4dns -> ", millis[i], nanos[i]));
            System.out.println(sw.stop());
            sw.reset();
        }
    }
}

実行結果

実行時間によって表示される時間単位(μs, ms, s)が動的に変わっているのが分かる。

    0ms   10ns -> 777.5 μs
    0ms  100ns -> 590.1 μs
    0ms 1000ns -> 704.9 μs
    1ms    0ns -> 811.9 μs
   10ms    0ns -> 9.868 ms
  100ms    0ns -> 99.69 ms
 1000ms    0ns -> 999.8 ms
10000ms    0ns -> 10.00 s
18
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?