• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2013 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.caliper.runner;
18 
19 import static java.math.RoundingMode.CEILING;
20 import static java.util.concurrent.TimeUnit.NANOSECONDS;
21 
22 import com.google.caliper.util.ShortDuration;
23 import com.google.common.base.Ticker;
24 import com.google.common.math.LongMath;
25 
26 /**
27  * A utility that calculates the finest granularity that can be expected from subsequent calls to
28  * {@link System#nanoTime()}.  Note that this utility necessarily invokes {@link System#nanoTime()}
29  * directly rather than using {@link Ticker} because the extra indirection might cause additional
30  * overhead.
31  */
32 final class NanoTimeGranularityTester {
33   private static final int TRIALS = 1000;
34 
testNanoTimeGranularity()35   ShortDuration testNanoTimeGranularity() {
36     long total = 0L;
37     for (int i = 0; i < TRIALS; i++) {
38       long first = System.nanoTime();
39       long second = System.nanoTime();
40       long third = System.nanoTime();
41       long fourth = System.nanoTime();
42       long fifth = System.nanoTime();
43       long sixth = System.nanoTime();
44       long seventh = System.nanoTime();
45       long eighth = System.nanoTime();
46       long ninth = System.nanoTime();
47       total += second - first;
48       total += third - second;
49       total += fourth - third;
50       total += fifth - fourth;
51       total += sixth - fifth;
52       total += seventh - sixth;
53       total += eighth - seventh;
54       total += ninth - eighth;
55     }
56     return ShortDuration.of(LongMath.divide(total, TRIALS * 8, CEILING), NANOSECONDS);
57   }
58 }
59