rclone/lib/mmap/mmap_test.go
Nick Craig-Wood 401cf81034 build: modernize Go usage
This commit modernizes Go usage. This was done with:

go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...

Then files needed to be `go fmt`ed and a few comments needed to be
restored.

The modernizations include replacing

- if/else conditional assignment by a call to the built-in min or max functions added in go1.21
- sort.Slice(x, func(i, j int) bool) { return s[i] < s[j] } by a call to slices.Sort(s), added in go1.21
- interface{} by the 'any' type added in go1.18
- append([]T(nil), s...) by slices.Clone(s) or slices.Concat(s), added in go1.21
- loop around an m[k]=v map update by a call to one of the Collect, Copy, Clone, or Insert functions from the maps package, added in go1.21
- []byte(fmt.Sprintf...) by fmt.Appendf(nil, ...), added in go1.19
- append(s[:i], s[i+1]...) by slices.Delete(s, i, i+1), added in go1.21
- a 3-clause for i := 0; i < n; i++ {} loop by for i := range n {}, added in go1.22
2025-02-28 11:31:14 +00:00

100 lines
2.0 KiB
Go

package mmap
import (
"fmt"
"testing"
"github.com/stretchr/testify/assert"
)
// Constants to control the benchmarking
const (
maxAllocs = 16 * 1024
)
func TestAllocFree(t *testing.T) {
const Size = 4096
b := MustAlloc(Size)
assert.Equal(t, Size, len(b))
// check we can write to all the memory
for i := range b {
b[i] = byte(i)
}
// Now free the memory
MustFree(b)
}
func BenchmarkAllocFree(b *testing.B) {
for _, dirty := range []bool{false, true} {
for size := 4096; size <= 32*1024*1024; size *= 2 {
b.Run(fmt.Sprintf("%dk,dirty=%v", size>>10, dirty), func(b *testing.B) {
for i := 0; i < b.N; i++ {
mem := MustAlloc(size)
if dirty {
mem[0] ^= 0xFF
}
MustFree(mem)
}
})
}
}
}
// benchmark the time alloc/free takes with lots of allocations already
func BenchmarkAllocFreeWithLotsOfAllocations(b *testing.B) {
const size = 4096
alloc := func(n int) (allocs [][]byte) {
for range n {
mem := MustAlloc(size)
mem[0] ^= 0xFF
allocs = append(allocs, mem)
}
return allocs
}
free := func(allocs [][]byte) {
for _, mem := range allocs {
MustFree(mem)
}
}
for preAllocs := 1; preAllocs <= maxAllocs; preAllocs *= 2 {
allocs := alloc(preAllocs)
b.Run(fmt.Sprintf("%d", preAllocs), func(b *testing.B) {
for i := 0; i < b.N; i++ {
mem := MustAlloc(size)
mem[0] ^= 0xFF
MustFree(mem)
}
})
free(allocs)
}
}
// benchmark the time alloc/free takes for lots of allocations
func BenchmarkAllocFreeForLotsOfAllocations(b *testing.B) {
const size = 4096
alloc := func(n int) (allocs [][]byte) {
for range n {
mem := MustAlloc(size)
mem[0] ^= 0xFF
allocs = append(allocs, mem)
}
return allocs
}
free := func(allocs [][]byte) {
for _, mem := range allocs {
MustFree(mem)
}
}
for preAllocs := 1; preAllocs <= maxAllocs; preAllocs *= 2 {
b.Run(fmt.Sprintf("%d", preAllocs), func(b *testing.B) {
for i := 0; i < b.N; i++ {
allocs := alloc(preAllocs)
free(allocs)
}
})
}
}