github.com/rclone/rclone@v1.66.1-0.20240517100346-7b89735ae726/lib/mmap/mmap_test.go (about) 1 package mmap 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 // Constants to control the benchmarking 11 const ( 12 maxAllocs = 16 * 1024 13 ) 14 15 func TestAllocFree(t *testing.T) { 16 const Size = 4096 17 18 b := MustAlloc(Size) 19 assert.Equal(t, Size, len(b)) 20 21 // check we can write to all the memory 22 for i := range b { 23 b[i] = byte(i) 24 } 25 26 // Now free the memory 27 MustFree(b) 28 } 29 30 func BenchmarkAllocFree(b *testing.B) { 31 for _, dirty := range []bool{false, true} { 32 for size := 4096; size <= 32*1024*1024; size *= 2 { 33 b.Run(fmt.Sprintf("%dk,dirty=%v", size>>10, dirty), func(b *testing.B) { 34 for i := 0; i < b.N; i++ { 35 mem := MustAlloc(size) 36 if dirty { 37 mem[0] ^= 0xFF 38 } 39 MustFree(mem) 40 } 41 }) 42 } 43 } 44 } 45 46 // benchmark the time alloc/free takes with lots of allocations already 47 func BenchmarkAllocFreeWithLotsOfAllocations(b *testing.B) { 48 const size = 4096 49 alloc := func(n int) (allocs [][]byte) { 50 for i := 0; i < n; i++ { 51 mem := MustAlloc(size) 52 mem[0] ^= 0xFF 53 allocs = append(allocs, mem) 54 } 55 return allocs 56 } 57 free := func(allocs [][]byte) { 58 for _, mem := range allocs { 59 MustFree(mem) 60 } 61 } 62 for preAllocs := 1; preAllocs <= maxAllocs; preAllocs *= 2 { 63 allocs := alloc(preAllocs) 64 b.Run(fmt.Sprintf("%d", preAllocs), func(b *testing.B) { 65 for i := 0; i < b.N; i++ { 66 mem := MustAlloc(size) 67 mem[0] ^= 0xFF 68 MustFree(mem) 69 } 70 }) 71 free(allocs) 72 } 73 } 74 75 // benchmark the time alloc/free takes for lots of allocations 76 func BenchmarkAllocFreeForLotsOfAllocations(b *testing.B) { 77 const size = 4096 78 alloc := func(n int) (allocs [][]byte) { 79 for i := 0; i < n; i++ { 80 mem := MustAlloc(size) 81 mem[0] ^= 0xFF 82 allocs = append(allocs, mem) 83 } 84 return allocs 85 } 86 free := func(allocs [][]byte) { 87 for _, mem := range allocs { 88 MustFree(mem) 89 } 90 } 91 for preAllocs := 1; preAllocs <= maxAllocs; preAllocs *= 2 { 92 b.Run(fmt.Sprintf("%d", preAllocs), func(b *testing.B) { 93 for i := 0; i < b.N; i++ { 94 allocs := alloc(preAllocs) 95 free(allocs) 96 } 97 }) 98 } 99 }