go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/experiments/matchmaker/pkg/sim/debug.go (about)

     1  /*
     2  
     3  Copyright (c) 2024 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package sim
     9  
    10  import (
    11  	"fmt"
    12  	"strings"
    13  	"time"
    14  
    15  	"go.charczuk.com/sdk/mathutil"
    16  )
    17  
    18  type Tag struct {
    19  	K string
    20  	V any
    21  }
    22  
    23  func log(message string, tags ...Tag) {
    24  	var tagStrings []string
    25  	for _, t := range tags {
    26  		tagStrings = append(tagStrings, fmt.Sprintf("%s=%v", t.K, t.V))
    27  	}
    28  	fmt.Println(message, strings.Join(tagStrings, " "))
    29  }
    30  
    31  func runtimeAssert(passed bool, panicMsg string) {
    32  	if !passed {
    33  		panic(panicMsg)
    34  	}
    35  }
    36  
    37  func logElapsed[T any](message string, fn func() T) T {
    38  	start := time.Now()
    39  	defer func() {
    40  		log(message, Tag{"elapsed", time.Since(start)})
    41  	}()
    42  	return fn()
    43  }
    44  
    45  var funcElapsed = map[string][]time.Duration{}
    46  
    47  func logElapsedFunc(label string, fn func()) {
    48  	start := time.Now()
    49  	defer func() {
    50  		funcElapsed[label] = append(funcElapsed[label], time.Since(start))
    51  	}()
    52  	fn()
    53  }
    54  
    55  func printFuncElapsed() {
    56  	for key, values := range funcElapsed {
    57  		fmin, fmax := mathutil.MinMax(values)
    58  		valuesSorted := mathutil.CopySort(values)
    59  		fp50 := mathutil.PercentileSorted(valuesSorted, 50.0)
    60  		fp75 := mathutil.PercentileSorted(valuesSorted, 75.0)
    61  		fp95 := mathutil.PercentileSorted(valuesSorted, 95.0)
    62  		fmt.Println(key, "stats")
    63  		fmt.Printf("\tmin: %v\n", fmin)
    64  		fmt.Printf("\tp50: %v\n", fp50)
    65  		fmt.Printf("\tp75: %v\n", fp75)
    66  		fmt.Printf("\tp95: %v\n", fp95)
    67  		fmt.Printf("\tmax: %v\n", fmax)
    68  	}
    69  }