cmd/evm: make warm-up before bench-run

This commit is contained in:
Martin Holst Swende 2024-11-08 14:01:45 +01:00
parent 1f84917da0
commit ca8beb9a73
No known key found for this signature in database
GPG key ID: 683B438C05A5DDF0

View file

@ -81,32 +81,46 @@ type execStats struct {
GasUsed uint64 `json:"gasUsed"` // the amount of gas used during execution GasUsed uint64 `json:"gasUsed"` // the amount of gas used during execution
} }
func timedExec(bench bool, execFunc func() ([]byte, uint64, error)) (output []byte, stats execStats, err error) { func timedExec(bench bool, execFunc func() ([]byte, uint64, error)) ([]byte, execStats, error) {
var gasUsed uint64
if bench { if bench {
// Do one warm-up run
output, gasUsed, err := execFunc()
result := testing.Benchmark(func(b *testing.B) { result := testing.Benchmark(func(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
output, gasUsed, err = execFunc() haveOutput, haveGasUsed, haveErr := execFunc()
if !bytes.Equal(haveOutput, output) {
b.Fatalf("output differs, have\n%x\nwant%x\n", haveOutput, output)
}
if haveGasUsed != gasUsed {
b.Fatalf("gas differs, have %v want%v", haveGasUsed, gasUsed)
}
if haveErr != err {
b.Fatalf("err differs, have %v want%v", haveErr, err)
}
} }
}) })
// Get the average execution time from the benchmarking result. // Get the average execution time from the benchmarking result.
// There are other useful stats here that could be reported. // There are other useful stats here that could be reported.
stats.Time = time.Duration(result.NsPerOp()) stats := execStats{
stats.Allocs = result.AllocsPerOp() Time: time.Duration(result.NsPerOp()),
stats.BytesAllocated = result.AllocedBytesPerOp() Allocs: result.AllocsPerOp(),
stats.GasUsed = gasUsed BytesAllocated: result.AllocedBytesPerOp(),
} else { GasUsed: gasUsed,
var memStatsBefore, memStatsAfter goruntime.MemStats }
goruntime.ReadMemStats(&memStatsBefore) return output, stats, err
startTime := time.Now() }
output, gasUsed, err = execFunc() var memStatsBefore, memStatsAfter goruntime.MemStats
stats.Time = time.Since(startTime) goruntime.ReadMemStats(&memStatsBefore)
goruntime.ReadMemStats(&memStatsAfter) t0 := time.Now()
stats.Allocs = int64(memStatsAfter.Mallocs - memStatsBefore.Mallocs) output, gasUsed, err := execFunc()
stats.BytesAllocated = int64(memStatsAfter.TotalAlloc - memStatsBefore.TotalAlloc) duration := time.Since(t0)
stats.GasUsed = gasUsed goruntime.ReadMemStats(&memStatsAfter)
stats := execStats{
Time: duration,
Allocs: int64(memStatsAfter.Mallocs - memStatsBefore.Mallocs),
BytesAllocated: int64(memStatsAfter.TotalAlloc - memStatsBefore.TotalAlloc),
GasUsed: gasUsed,
} }
return output, stats, err return output, stats, err
} }