github.com/haraldrudell/parl@v0.4.176/goid/go-id_test.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package goid
     7  
     8  import (
     9  	"os"
    10  	"runtime"
    11  	"runtime/debug"
    12  	"strconv"
    13  	"strings"
    14  	"testing"
    15  	"time"
    16  
    17  	"github.com/haraldrudell/parl"
    18  )
    19  
    20  func TestGoID(t *testing.T) {
    21  	runtGoroutinePrefix := "goroutine "
    22  
    23  	// get expected ThreadID
    24  	var expectedID parl.ThreadID
    25  	s := strings.TrimPrefix(string(debug.Stack()), runtGoroutinePrefix)
    26  	if index := strings.Index(s, "\x20"); index != -1 {
    27  		var e error
    28  		var u64 uint64
    29  		if u64, e = strconv.ParseUint(s[:index], 10, 64); e != nil {
    30  			panic(e)
    31  		}
    32  		expectedID = parl.ThreadID(u64)
    33  	} else {
    34  		t.Error("debug.Stack failed")
    35  	}
    36  
    37  	actual := GoID()
    38  	if actual != expectedID {
    39  		t.Errorf("GoRoutineID bad: %q expected %q", actual, expectedID)
    40  	}
    41  }
    42  
    43  /*
    44  2022-04-08 host: c66 go version: go1.18
    45  the selected number of iterations: 480,165
    46  execution time: 2.364 μs
    47  the code allocated 1,664 bytes i 2 allocations
    48  
    49  # A function call is 0.3215 ns
    50  
    51  goos: darwin
    52  goarch: arm64
    53  pkg: github.com/haraldrudell/parl/goid
    54  BenchmarkGoID-10    	  480165	      2364 ns/op	    1664 B/op	       2 allocs/op
    55  */
    56  func BenchmarkData(b *testing.B) {
    57  	// a global variable is undefined every time
    58  	// os.MkdirTemp returns a different directory every time
    59  	if hostname, err := os.Hostname(); err != nil {
    60  		b.Errorf("os.Hostname FAIL: %v", err)
    61  	} else {
    62  		if index := strings.Index(hostname, "."); index != -1 {
    63  			hostname = hostname[:index]
    64  		}
    65  		today := time.Now().Format("2006-01-02")
    66  		b.Logf("%s host: %s go version: %s", today, hostname, runtime.Version())
    67  	}
    68  	for i := 0; i < b.N; i++ {
    69  		GoID()
    70  	}
    71  }
    72  
    73  func BenchmarkGoID(b *testing.B) {
    74  	for i := 0; i < b.N; i++ {
    75  		GoID()
    76  	}
    77  }
    78  
    79  func BenchmarkCall(b *testing.B) {
    80  	for i := 0; i < b.N; i++ {
    81  		someFunc()
    82  	}
    83  }
    84  
    85  func someFunc() {}