1/*
2Package gomega/gmeasure provides support for benchmarking and measuring code.  It is intended as a more robust replacement for Ginkgo V1's Measure nodes.
3
4**gmeasure IS CURRENTLY IN BETA - THE API MAY CHANGE IN THE NEAR-FUTURE.  gmeasure WILL BE CONSIDERED GA WHEN Ginkgo V2 IS GA.
5
6gmeasure is organized around the metaphor of an Experiment that can record multiple Measurements.  A Measurement is a named collection of data points and gmeasure supports
7measuring Values (of type float64) and Durations (of type time.Duration).
8
9Experiments allows the user to record Measurements directly by passing in Values (i.e. float64) or Durations (i.e. time.Duration)
10or to measure measurements by passing in functions to measure.  When measuring functions Experiments take care of timing the duration of functions (for Duration measurements)
11and/or recording returned values (for Value measurements).  Experiments also support sampling functions - when told to sample Experiments will run functions repeatedly
12and measure and record results.  The sampling behavior is configured by passing in a SamplingConfig that can control the maximum number of samples, the maximum duration for sampling (or both)
13and the number of concurrent samples to take.
14
15Measurements can be decorated with additional information.  This is supported by passing in special typed decorators when recording measurements.  These include:
16
17- Units("any string") - to attach units to a Value Measurement (Duration Measurements always have units of "duration")
18- Style("any Ginkgo color style string") - to attach styling to a Measurement.  This styling is used when rendering console information about the measurement in reports.  Color style strings are documented at TODO.
19- Precision(integer or time.Duration) - to attach precision to a Measurement.  This controls how many decimal places to show for Value Measurements and how to round Duration Measurements when rendering them to screen.
20
21In addition, individual data points in a Measurement can be annotated with an Annotation("any string").  The annotation is associated with the individual data point and is intended to convey additional context about the data point.
22
23Once measurements are complete, an Experiment can generate a comprehensive report by calling its String() or ColorableString() method.
24
25Users can also access and analyze the resulting Measurements directly.  Use Experiment.Get(NAME) to fetch the Measurement named NAME.  This returned struct will have fields containing
26all the data points and annotations recorded by the experiment.  You can subsequently fetch the Measurement.Stats() to get a Stats struct that contains basic statistical information about the
27Measurement (min, max, median, mean, standard deviation).  You can order these Stats objects using RankStats() to identify best/worst performers across multpile experiments or measurements.
28
29gmeasure also supports caching Experiments via an ExperimentCache.  The cache supports storing and retreiving experiments by name and version.  This allows you to rerun code without
30repeating expensive experiments that may not have changed (which can be controlled by the cache version number).  It also enables you to compare new experiment runs with older runs to detect
31variations in performance/behavior.
32
33When used with Ginkgo, you can emit experiment reports and encode them in test reports easily using Ginkgo V2's support for Report Entries.
34Simply pass your experiment to AddReportEntry to get a report every time the tests run.  You can also use AddReportEntry with Measurements to emit all the captured data
35and Rankings to emit measurement summaries in rank order.
36
37Finally, Experiments provide an additional mechanism to measure durations called a Stopwatch.  The Stopwatch makes it easy to pepper code with statements that measure elapsed time across
38different sections of code and can be useful when debugging or evaluating bottlenecks in a given codepath.
39*/
40package gmeasure
41
42import (
43	"fmt"
44	"math"
45	"reflect"
46	"sync"
47	"time"
48
49	"github.com/onsi/gomega/gmeasure/table"
50)
51
52/*
53SamplingConfig configures the Sample family of experiment methods.
54These methods invoke passed-in functions repeatedly to sample and record a given measurement.
55SamplingConfig is used to control the maximum number of samples or time spent sampling (or both).  When both are specified sampling ends as soon as one of the conditions is met.
56SamplingConfig can also ensure a minimum interval between samples and can enable concurrent sampling.
57*/
58type SamplingConfig struct {
59	// N - the maximum number of samples to record
60	N int
61	// Duration - the maximum amount of time to spend recording samples
62	Duration time.Duration
63	// MinSamplingInterval - the minimum time that must elapse between samplings.  It is an error to specify both MinSamplingInterval and NumParallel.
64	MinSamplingInterval time.Duration
65	// NumParallel - the number of parallel workers to spin up to record samples.  It is an error to specify both MinSamplingInterval and NumParallel.
66	NumParallel int
67}
68
69// The Units decorator allows you to specify units (an arbitrary string) when recording values.  It is ignored when recording durations.
70//
71//     e := gmeasure.NewExperiment("My Experiment")
72//     e.RecordValue("length", 3.141, gmeasure.Units("inches"))
73//
74// Units are only set the first time a value of a given name is recorded.  In the example above any subsequent calls to e.RecordValue("length", X) will maintain the "inches" units even if a new set of Units("UNIT") are passed in later.
75type Units string
76
77// The Annotation decorator allows you to attach an annotation to a given recorded data-point:
78//
79// For example:
80//
81//     e := gmeasure.NewExperiment("My Experiment")
82//     e.RecordValue("length", 3.141, gmeasure.Annotation("bob"))
83//     e.RecordValue("length", 2.71, gmeasure.Annotation("jane"))
84//
85// ...will result in a Measurement named "length" that records two values )[3.141, 2.71]) annotation with (["bob", "jane"])
86type Annotation string
87
88// The Style decorator allows you to associate a style with a measurement.  This is used to generate colorful console reports using Ginkgo V2's
89// console formatter.  Styles are strings in curly brackets that correspond to a color or style.
90//
91// For example:
92//
93//     e := gmeasure.NewExperiment("My Experiment")
94//     e.RecordValue("length", 3.141, gmeasure.Style("{{blue}}{{bold}}"))
95//     e.RecordValue("length", 2.71)
96//     e.RecordDuration("cooking time", 3 * time.Second, gmeasure.Style("{{red}}{{underline}}"))
97//     e.RecordDuration("cooking time", 2 * time.Second)
98//
99// will emit a report with blue bold entries for the length measurement and red underlined entries for the cooking time measurement.
100//
101// Units are only set the first time a value or duration of a given name is recorded.  In the example above any subsequent calls to e.RecordValue("length", X) will maintain the "{{blue}}{{bold}}" style even if a new Style is passed in later.
102type Style string
103
104// The PrecisionBundle decorator controls the rounding of value and duration measurements.  See Precision().
105type PrecisionBundle struct {
106	Duration    time.Duration
107	ValueFormat string
108}
109
110// Precision() allows you to specify the precision of a value or duration measurement - this precision is used when rendering the measurement to screen.
111//
112// To control the precision of Value measurements, pass Precision an integer.  This will denote the number of decimal places to render (equivalen to the format string "%.Nf")
113// To control the precision of Duration measurements, pass Precision a time.Duration.  Duration measurements will be rounded oo the nearest time.Duration when rendered.
114//
115// For example:
116//
117//     e := gmeasure.NewExperiment("My Experiment")
118//     e.RecordValue("length", 3.141, gmeasure.Precision(2))
119//     e.RecordValue("length", 2.71)
120//     e.RecordDuration("cooking time", 3214 * time.Millisecond, gmeasure.Precision(100*time.Millisecond))
121//     e.RecordDuration("cooking time", 2623 * time.Millisecond)
122func Precision(p interface{}) PrecisionBundle {
123	out := DefaultPrecisionBundle
124	switch reflect.TypeOf(p) {
125	case reflect.TypeOf(time.Duration(0)):
126		out.Duration = p.(time.Duration)
127	case reflect.TypeOf(int(0)):
128		out.ValueFormat = fmt.Sprintf("%%.%df", p.(int))
129	default:
130		panic("invalid precision type, must be time.Duration or int")
131	}
132	return out
133}
134
135// DefaultPrecisionBundle captures the default precisions for Vale and Duration measurements.
136var DefaultPrecisionBundle = PrecisionBundle{
137	Duration:    100 * time.Microsecond,
138	ValueFormat: "%.3f",
139}
140
141type extractedDecorations struct {
142	annotation      Annotation
143	units           Units
144	precisionBundle PrecisionBundle
145	style           Style
146}
147
148func extractDecorations(args []interface{}) extractedDecorations {
149	var out extractedDecorations
150	out.precisionBundle = DefaultPrecisionBundle
151
152	for _, arg := range args {
153		switch reflect.TypeOf(arg) {
154		case reflect.TypeOf(out.annotation):
155			out.annotation = arg.(Annotation)
156		case reflect.TypeOf(out.units):
157			out.units = arg.(Units)
158		case reflect.TypeOf(out.precisionBundle):
159			out.precisionBundle = arg.(PrecisionBundle)
160		case reflect.TypeOf(out.style):
161			out.style = arg.(Style)
162		default:
163			panic(fmt.Sprintf("unrecognized argument %#v", arg))
164		}
165	}
166
167	return out
168}
169
170/*
171Experiment is gmeasure's core data type.  You use experiments to record Measurements and generate reports.
172Experiments are thread-safe and all methods can be called from multiple goroutines.
173*/
174type Experiment struct {
175	Name string
176
177	// Measurements includes all Measurements recorded by this experiment.  You should access them by name via Get() and GetStats()
178	Measurements Measurements
179	lock         *sync.Mutex
180}
181
182/*
183NexExperiment creates a new experiment with the passed-in name.
184
185When using Ginkgo we recommend immediately registering the experiment as a ReportEntry:
186
187	experiment = NewExperiment("My Experiment")
188	AddReportEntry(experiment.Name, experiment)
189
190this will ensure an experiment report is emitted as part of the test output and exported with any test reports.
191*/
192func NewExperiment(name string) *Experiment {
193	experiment := &Experiment{
194		Name: name,
195		lock: &sync.Mutex{},
196	}
197	return experiment
198}
199
200func (e *Experiment) report(enableStyling bool) string {
201	t := table.NewTable()
202	t.TableStyle.EnableTextStyling = enableStyling
203	t.AppendRow(table.R(
204		table.C("Name"), table.C("N"), table.C("Min"), table.C("Median"), table.C("Mean"), table.C("StdDev"), table.C("Max"),
205		table.Divider("="),
206		"{{bold}}",
207	))
208
209	for _, measurement := range e.Measurements {
210		r := table.R(measurement.Style)
211		t.AppendRow(r)
212		switch measurement.Type {
213		case MeasurementTypeNote:
214			r.AppendCell(table.C(measurement.Note))
215		case MeasurementTypeValue, MeasurementTypeDuration:
216			name := measurement.Name
217			if measurement.Units != "" {
218				name += " [" + measurement.Units + "]"
219			}
220			r.AppendCell(table.C(name))
221			r.AppendCell(measurement.Stats().cells()...)
222		}
223	}
224
225	out := e.Name + "\n"
226	if enableStyling {
227		out = "{{bold}}" + out + "{{/}}"
228	}
229	out += t.Render()
230	return out
231}
232
233/*
234ColorableString returns a Ginkgo formatted summary of the experiment and all its Measurements.
235It is called automatically by Ginkgo's reporting infrastructure when the Experiment is registered as a ReportEntry via AddReportEntry.
236*/
237func (e *Experiment) ColorableString() string {
238	return e.report(true)
239}
240
241/*
242ColorableString returns an unformatted summary of the experiment and all its Measurements.
243*/
244func (e *Experiment) String() string {
245	return e.report(false)
246}
247
248/*
249RecordNote records a Measurement of type MeasurementTypeNote - this is simply a textual note to annotate the experiment.  It will be emitted in any experiment reports.
250
251RecordNote supports the Style() decoration.
252*/
253func (e *Experiment) RecordNote(note string, args ...interface{}) {
254	decorations := extractDecorations(args)
255
256	e.lock.Lock()
257	defer e.lock.Unlock()
258	e.Measurements = append(e.Measurements, Measurement{
259		ExperimentName: e.Name,
260		Type:           MeasurementTypeNote,
261		Note:           note,
262		Style:          string(decorations.style),
263	})
264}
265
266/*
267RecordDuration records the passed-in duration on a Duration Measurement with the passed-in name.  If the Measurement does not exist it is created.
268
269RecordDuration supports the Style(), Precision(), and Annotation() decorations.
270*/
271func (e *Experiment) RecordDuration(name string, duration time.Duration, args ...interface{}) {
272	decorations := extractDecorations(args)
273	e.recordDuration(name, duration, decorations)
274}
275
276/*
277MeasureDuration runs the passed-in callback and times how long it takes to complete.  The resulting duration is recorded on a Duration Measurement with the passed-in name.  If the Measurement does not exist it is created.
278
279MeasureDuration supports the Style(), Precision(), and Annotation() decorations.
280*/
281func (e *Experiment) MeasureDuration(name string, callback func(), args ...interface{}) time.Duration {
282	t := time.Now()
283	callback()
284	duration := time.Since(t)
285	e.RecordDuration(name, duration, args...)
286	return duration
287}
288
289/*
290SampleDuration samples the passed-in callback and times how long it takes to complete each sample.
291The resulting durations are recorded on a Duration Measurement with the passed-in name.  If the Measurement does not exist it is created.
292
293The callback is given a zero-based index that increments by one between samples.  The Sampling is configured via the passed-in SamplingConfig
294
295SampleDuration supports the Style(), Precision(), and Annotation() decorations.  When passed an Annotation() the same annotation is applied to all sample measurements.
296*/
297func (e *Experiment) SampleDuration(name string, callback func(idx int), samplingConfig SamplingConfig, args ...interface{}) {
298	decorations := extractDecorations(args)
299	e.Sample(func(idx int) {
300		t := time.Now()
301		callback(idx)
302		duration := time.Since(t)
303		e.recordDuration(name, duration, decorations)
304	}, samplingConfig)
305}
306
307/*
308SampleDuration samples the passed-in callback and times how long it takes to complete each sample.
309The resulting durations are recorded on a Duration Measurement with the passed-in name.  If the Measurement does not exist it is created.
310
311The callback is given a zero-based index that increments by one between samples.  The callback must return an Annotation - this annotation is attached to the measured duration.
312
313The Sampling is configured via the passed-in SamplingConfig
314
315SampleAnnotatedDuration supports the Style() and Precision() decorations.
316*/
317func (e *Experiment) SampleAnnotatedDuration(name string, callback func(idx int) Annotation, samplingConfig SamplingConfig, args ...interface{}) {
318	decorations := extractDecorations(args)
319	e.Sample(func(idx int) {
320		t := time.Now()
321		decorations.annotation = callback(idx)
322		duration := time.Since(t)
323		e.recordDuration(name, duration, decorations)
324	}, samplingConfig)
325}
326
327func (e *Experiment) recordDuration(name string, duration time.Duration, decorations extractedDecorations) {
328	e.lock.Lock()
329	defer e.lock.Unlock()
330	idx := e.Measurements.IdxWithName(name)
331	if idx == -1 {
332		measurement := Measurement{
333			ExperimentName:  e.Name,
334			Type:            MeasurementTypeDuration,
335			Name:            name,
336			Units:           "duration",
337			Durations:       []time.Duration{duration},
338			PrecisionBundle: decorations.precisionBundle,
339			Style:           string(decorations.style),
340			Annotations:     []string{string(decorations.annotation)},
341		}
342		e.Measurements = append(e.Measurements, measurement)
343	} else {
344		if e.Measurements[idx].Type != MeasurementTypeDuration {
345			panic(fmt.Sprintf("attempting to record duration with name '%s'.  That name is already in-use for recording values.", name))
346		}
347		e.Measurements[idx].Durations = append(e.Measurements[idx].Durations, duration)
348		e.Measurements[idx].Annotations = append(e.Measurements[idx].Annotations, string(decorations.annotation))
349	}
350}
351
352/*
353NewStopwatch() returns a stopwatch configured to record duration measurements with this experiment.
354*/
355func (e *Experiment) NewStopwatch() *Stopwatch {
356	return newStopwatch(e)
357}
358
359/*
360RecordValue records the passed-in value on a Value Measurement with the passed-in name.  If the Measurement does not exist it is created.
361
362RecordValue supports the Style(), Units(), Precision(), and Annotation() decorations.
363*/
364func (e *Experiment) RecordValue(name string, value float64, args ...interface{}) {
365	decorations := extractDecorations(args)
366	e.recordValue(name, value, decorations)
367}
368
369/*
370MeasureValue runs the passed-in callback and records the return value on a Value Measurement with the passed-in name.  If the Measurement does not exist it is created.
371
372MeasureValue supports the Style(), Units(), Precision(), and Annotation() decorations.
373*/
374func (e *Experiment) MeasureValue(name string, callback func() float64, args ...interface{}) float64 {
375	value := callback()
376	e.RecordValue(name, value, args...)
377	return value
378}
379
380/*
381SampleValue samples the passed-in callback and records the return value on a Value Measurement with the passed-in name. If the Measurement does not exist it is created.
382
383The callback is given a zero-based index that increments by one between samples.  The callback must return a float64.  The Sampling is configured via the passed-in SamplingConfig
384
385SampleValue supports the Style(), Units(), Precision(), and Annotation() decorations.  When passed an Annotation() the same annotation is applied to all sample measurements.
386*/
387func (e *Experiment) SampleValue(name string, callback func(idx int) float64, samplingConfig SamplingConfig, args ...interface{}) {
388	decorations := extractDecorations(args)
389	e.Sample(func(idx int) {
390		value := callback(idx)
391		e.recordValue(name, value, decorations)
392	}, samplingConfig)
393}
394
395/*
396SampleAnnotatedValue samples the passed-in callback and records the return value on a Value Measurement with the passed-in name. If the Measurement does not exist it is created.
397
398The callback is given a zero-based index that increments by one between samples.  The callback must return a float64 and an Annotation - the annotation is attached to the recorded value.
399
400The Sampling is configured via the passed-in SamplingConfig
401
402SampleValue supports the Style(), Units(), and Precision() decorations.
403*/
404func (e *Experiment) SampleAnnotatedValue(name string, callback func(idx int) (float64, Annotation), samplingConfig SamplingConfig, args ...interface{}) {
405	decorations := extractDecorations(args)
406	e.Sample(func(idx int) {
407		var value float64
408		value, decorations.annotation = callback(idx)
409		e.recordValue(name, value, decorations)
410	}, samplingConfig)
411}
412
413func (e *Experiment) recordValue(name string, value float64, decorations extractedDecorations) {
414	e.lock.Lock()
415	defer e.lock.Unlock()
416	idx := e.Measurements.IdxWithName(name)
417	if idx == -1 {
418		measurement := Measurement{
419			ExperimentName:  e.Name,
420			Type:            MeasurementTypeValue,
421			Name:            name,
422			Style:           string(decorations.style),
423			Units:           string(decorations.units),
424			PrecisionBundle: decorations.precisionBundle,
425			Values:          []float64{value},
426			Annotations:     []string{string(decorations.annotation)},
427		}
428		e.Measurements = append(e.Measurements, measurement)
429	} else {
430		if e.Measurements[idx].Type != MeasurementTypeValue {
431			panic(fmt.Sprintf("attempting to record value with name '%s'.  That name is already in-use for recording durations.", name))
432		}
433		e.Measurements[idx].Values = append(e.Measurements[idx].Values, value)
434		e.Measurements[idx].Annotations = append(e.Measurements[idx].Annotations, string(decorations.annotation))
435	}
436}
437
438/*
439Sample samples the passed-in callback repeatedly.  The sampling is governed by the passed in SamplingConfig.
440
441The SamplingConfig can limit the total number of samples and/or the total time spent sampling the callback.
442The SamplingConfig can also instruct Sample to run with multiple concurrent workers.
443
444The callback is called with a zero-based index that incerements by one between samples.
445*/
446func (e *Experiment) Sample(callback func(idx int), samplingConfig SamplingConfig) {
447	if samplingConfig.N == 0 && samplingConfig.Duration == 0 {
448		panic("you must specify at least one of SamplingConfig.N and SamplingConfig.Duration")
449	}
450	if samplingConfig.MinSamplingInterval > 0 && samplingConfig.NumParallel > 1 {
451		panic("you cannot specify both SamplingConfig.MinSamplingInterval and SamplingConfig.NumParallel")
452	}
453	maxTime := time.Now().Add(100000 * time.Hour)
454	if samplingConfig.Duration > 0 {
455		maxTime = time.Now().Add(samplingConfig.Duration)
456	}
457	maxN := math.MaxInt64
458	if samplingConfig.N > 0 {
459		maxN = samplingConfig.N
460	}
461	numParallel := 1
462	if samplingConfig.NumParallel > numParallel {
463		numParallel = samplingConfig.NumParallel
464	}
465	minSamplingInterval := samplingConfig.MinSamplingInterval
466
467	work := make(chan int)
468	if numParallel > 1 {
469		for worker := 0; worker < numParallel; worker++ {
470			go func() {
471				for idx := range work {
472					callback(idx)
473				}
474			}()
475		}
476	}
477
478	idx := 0
479	var avgDt time.Duration
480	for {
481		t := time.Now()
482		if numParallel > 1 {
483			work <- idx
484		} else {
485			callback(idx)
486		}
487		dt := time.Since(t)
488		if numParallel == 1 && dt < minSamplingInterval {
489			time.Sleep(minSamplingInterval - dt)
490			dt = time.Since(t)
491		}
492		if idx >= numParallel {
493			avgDt = (avgDt*time.Duration(idx-numParallel) + dt) / time.Duration(idx-numParallel+1)
494		}
495		idx += 1
496		if idx >= maxN {
497			return
498		}
499		if time.Now().Add(avgDt).After(maxTime) {
500			return
501		}
502	}
503}
504
505/*
506Get returns the Measurement with the associated name.  If no Measurement is found a zero Measurement{} is returned.
507*/
508func (e *Experiment) Get(name string) Measurement {
509	e.lock.Lock()
510	defer e.lock.Unlock()
511	idx := e.Measurements.IdxWithName(name)
512	if idx == -1 {
513		return Measurement{}
514	}
515	return e.Measurements[idx]
516}
517
518/*
519GetStats returns the Stats for the Measurement with the associated name.  If no Measurement is found a zero Stats{} is returned.
520
521experiment.GetStats(name) is equivalent to experiment.Get(name).Stats()
522*/
523func (e *Experiment) GetStats(name string) Stats {
524	measurement := e.Get(name)
525	e.lock.Lock()
526	defer e.lock.Unlock()
527	return measurement.Stats()
528}
529