github.com/cockroachdb/cockroachdb-parser@v0.23.3-0.20240213214944-911057d40c9a/pkg/util/grunning/grunning.go (about)

     1  // Copyright 2022 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  // Package grunning is a library that's able to retrieve on-CPU running time for
    12  // individual goroutines. It relies on using a patched Go and provides a
    13  // primitive for fine-grained CPU attribution and control. See #82356 for more
    14  // details.
    15  package grunning
    16  
    17  import "time"
    18  
    19  // Time returns the time spent by the current goroutine in the running state.
    20  func Time() time.Duration {
    21  	return time.Duration(grunningnanos())
    22  }
    23  
    24  // Difference is a helper function to compute the absolute difference between
    25  // two durations.
    26  func Difference(a, b time.Duration) time.Duration {
    27  	diff := a.Nanoseconds() - b.Nanoseconds()
    28  	if diff < 0 {
    29  		diff = -diff
    30  	}
    31  	return time.Duration(diff)
    32  }
    33  
    34  // Elapsed returns the running time spent doing some piece of work, with
    35  // grunning.Time() measurements from the start and end.
    36  //
    37  // NB: This only exists due to grunning.Time()'s non-monotonicity, a bug in our
    38  // runtime patch: https://github.com/cockroachdb/cockroachdb-parser/issues/95529. We can
    39  // get rid of this, keeping just grunning.Difference(), if that bug is fixed.
    40  // The bug results in slight {over,under}-estimation of the running time (the
    41  // latter breaking monotonicity), but is livable with our current uses of this
    42  // library.
    43  func Elapsed(start, end time.Duration) time.Duration {
    44  	diff := end.Nanoseconds() - start.Nanoseconds()
    45  	if diff < 0 {
    46  		diff = 0
    47  	}
    48  	return time.Duration(diff)
    49  }
    50  
    51  // Supported returns true iff per-goroutine running time is available in this
    52  // build. We use a patched Go runtime for all platforms officially supported for
    53  // CRDB when built using Bazel.
    54  func Supported() bool {
    55  	return supported()
    56  }