github.com/loov/hrtime@v1.0.3/tsc_test.go (about)

     1  // +build !race
     2  
     3  package hrtime_test
     4  
     5  import (
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/loov/hrtime"
    10  )
    11  
    12  func TestCountCalibration(t *testing.T) {
    13  	if !hrtime.TSCSupported() {
    14  		t.Skip("Cycle counting not supported")
    15  	}
    16  
    17  	start := hrtime.TSC()
    18  	for i := 0; i < 64; i++ {
    19  		empty()
    20  	}
    21  	stop := hrtime.TSC()
    22  
    23  	if stop-start < hrtime.TSCOverhead() {
    24  		t.Errorf("overhead is larger than delta: %v-%v=%v overhead:%v", stop, start, stop-start, hrtime.TSCOverhead())
    25  	}
    26  }
    27  
    28  func TestCountPrecision(t *testing.T) {
    29  	if !hrtime.TSCSupported() {
    30  		t.Skip("Cycle counting not supported")
    31  	}
    32  
    33  	t.Logf("Conversion 1000000 count = %v", hrtime.Count(1000000).ApproxDuration())
    34  
    35  	const N = 8 << 10
    36  
    37  	startnano := hrtime.Now()
    38  	start := hrtime.TSC()
    39  	for i := 0; i < N; i++ {
    40  		empty()
    41  	}
    42  	stop := hrtime.TSC()
    43  	stopnano := hrtime.Now()
    44  
    45  	loopTime := stop - start - 2*hrtime.TSCOverhead()
    46  	wallTime := stopnano - startnano - 2*hrtime.Overhead() - 2*hrtime.TSCOverhead().ApproxDuration()
    47  
    48  	approxConversionDrift := wallTime - loopTime.ApproxDuration()
    49  	if approxConversionDrift < 0 {
    50  		approxConversionDrift *= -1
    51  	}
    52  	if approxConversionDrift > 2*hrtime.Overhead()+500*time.Nanosecond {
    53  		t.Logf("drift: too large %v (loopTime:%v, wallTime:%v)", approxConversionDrift, loopTime.ApproxDuration(), wallTime)
    54  	}
    55  
    56  	// we expect each call to take at least 1 nanos
    57  	if loopTime.ApproxDuration() < N {
    58  		t.Errorf("slow: loop time took %v", loopTime)
    59  	}
    60  	// we expect no call to take more than 20 nanos
    61  	if loopTime.ApproxDuration() > 20*N {
    62  		t.Errorf("fast: loop time took %v", loopTime)
    63  	}
    64  }
    65  
    66  func BenchmarkTSC(b *testing.B) {
    67  	if !hrtime.TSCSupported() {
    68  		b.Skip("Cycle counting not supported")
    69  	}
    70  
    71  	for i := 0; i < b.N; i++ {
    72  		hrtime.TSC()
    73  	}
    74  }