-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Benchmarking with Avg and Mean
- Loading branch information
1 parent
b156a78
commit 424fac0
Showing
1 changed file
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,51 @@ | ||
package Misc | ||
|
||
import ( | ||
"github.com/RENCI/GoUtils/Collections" | ||
"time" | ||
) | ||
|
||
type BenchmarkResult struct { | ||
Name string | ||
Iterations Collections.List[time.Duration] | ||
Average time.Duration | ||
Median time.Duration | ||
} | ||
|
||
func Benchmark(name string, iterations int, f func()) *BenchmarkResult { | ||
var br = &BenchmarkResult{ | ||
Name: name, | ||
Iterations: Collections.NewList[time.Duration](), | ||
} | ||
|
||
for i := 0; i < iterations; i++ { | ||
start := time.Now() | ||
f() | ||
br.Iterations.Add(time.Since(start)) | ||
} | ||
|
||
return br | ||
} | ||
|
||
func (this *BenchmarkResult) Calculate() { | ||
if this.Iterations.Size() == 0 { | ||
return | ||
} | ||
var sum time.Duration | ||
|
||
this.Iterations.ForEach(func(v time.Duration) { | ||
sum += v | ||
}) | ||
|
||
this.Average = sum / time.Duration(this.Iterations.Size()) | ||
this.Iterations.Sort(func(item1 time.Duration, item2 time.Duration) int { | ||
if item1 > item2 { | ||
return 1 | ||
} else if item1 == item2 { | ||
return 0 | ||
} else { | ||
return -1 | ||
} | ||
}) | ||
this.Median = this.Iterations.Get(this.Iterations.Size() / 2) | ||
} |