github.com/c9s/go@v0.0.0-20180120015821-984e81f64e0c/src/runtime/vdso_linux_test.go (about)

     1  // Copyright 2017 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // +build linux
     6  // +build 386 amd64
     7  
     8  package runtime_test
     9  
    10  import (
    11  	"testing"
    12  	"time"
    13  	_ "unsafe"
    14  )
    15  
    16  // These tests are a little risky because they overwrite the __vdso_clock_gettime_sym value.
    17  // It's normally initialized at startup and remains unchanged after that.
    18  
    19  //go:linkname __vdso_clock_gettime_sym runtime.__vdso_clock_gettime_sym
    20  var __vdso_clock_gettime_sym uintptr
    21  
    22  func TestClockVDSOAndFallbackPaths(t *testing.T) {
    23  	// Check that we can call walltime() and nanotime() with and without their (1st) fast-paths.
    24  	// This just checks that fast and fallback paths can be called, rather than testing their
    25  	// results.
    26  	//
    27  	// Call them indirectly via time.Now(), so we don't need auxiliary .s files to allow us to
    28  	// use go:linkname to refer to the functions directly.
    29  
    30  	save := __vdso_clock_gettime_sym
    31  	if save == 0 {
    32  		t.Log("__vdso_clock_gettime symbol not found; fallback path will be used by default")
    33  	}
    34  
    35  	// Call with fast-path enabled (if vDSO symbol found at startup)
    36  	time.Now()
    37  
    38  	// Call with fast-path disabled
    39  	__vdso_clock_gettime_sym = 0
    40  	time.Now()
    41  	__vdso_clock_gettime_sym = save
    42  }
    43  
    44  func BenchmarkClockVDSOAndFallbackPaths(b *testing.B) {
    45  	run := func(b *testing.B) {
    46  		for i := 0; i < b.N; i++ {
    47  			// Call via time.Now() - see comment in test above.
    48  			time.Now()
    49  		}
    50  	}
    51  
    52  	save := __vdso_clock_gettime_sym
    53  	b.Run("vDSO", run)
    54  	__vdso_clock_gettime_sym = 0
    55  	b.Run("Fallback", run)
    56  	__vdso_clock_gettime_sym = save
    57  }
    58  
    59  func BenchmarkTimeNow(b *testing.B) {
    60  	for i := 0; i < b.N; i++ {
    61  		time.Now()
    62  	}
    63  }