github.com/zuoyebang/bitalosdb@v1.1.1-0.20240516111551-79a8c4d8ce20/internal/vfs/syncing_file_linux_test.go (about) 1 // Copyright 2021 The Bitalosdb author(hustxrb@163.com) and other contributors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 //go:build linux && !arm 16 17 package vfs 18 19 import ( 20 "fmt" 21 "os" 22 "syscall" 23 "testing" 24 "unsafe" 25 ) 26 27 func TestSyncRangeSmokeTest(t *testing.T) { 28 testCases := []struct { 29 err error 30 expected bool 31 }{ 32 {nil, true}, 33 {syscall.EINVAL, true}, 34 {syscall.ENOSYS, false}, 35 } 36 for i, c := range testCases { 37 t.Run("", func(t *testing.T) { 38 ok := syncRangeSmokeTest(uintptr(i), 39 func(fd int, off int64, n int64, flags int) (err error) { 40 if i != fd { 41 t.Fatalf("expected fd %d, but got %d", i, fd) 42 } 43 return c.err 44 }) 45 if c.expected != ok { 46 t.Fatalf("expected %t, but got %t: %v", c.expected, ok, c.err) 47 } 48 }) 49 } 50 } 51 52 func BenchmarkDirectIOWrite(b *testing.B) { 53 const targetSize = 16 << 20 54 const alignment = 4096 55 56 var wsizes []int 57 if testing.Verbose() { 58 wsizes = []int{4 << 10, 8 << 10, 16 << 10, 32 << 10} 59 } else { 60 wsizes = []int{4096} 61 } 62 63 for _, wsize := range wsizes { 64 b.Run(fmt.Sprintf("wsize=%d", wsize), func(b *testing.B) { 65 tmpf, err := os.CreateTemp("", "bitalosdb-db-syncing-file-") 66 if err != nil { 67 b.Fatal(err) 68 } 69 filename := tmpf.Name() 70 _ = tmpf.Close() 71 defer os.Remove(filename) 72 73 var f *os.File 74 var size int 75 buf := make([]byte, wsize+alignment) 76 if a := uintptr(unsafe.Pointer(&buf[0])) & uintptr(alignment-1); a != 0 { 77 buf = buf[alignment-a:] 78 } 79 buf = buf[:wsize] 80 init := true 81 82 b.SetBytes(int64(len(buf))) 83 b.ResetTimer() 84 for i := 0; i < b.N; i++ { 85 if f == nil { 86 b.StopTimer() 87 f, err = os.OpenFile(filename, syscall.O_DIRECT|os.O_RDWR, 0666) 88 if err != nil { 89 b.Fatal(err) 90 } 91 if init { 92 for size = 0; size < targetSize; size += len(buf) { 93 if _, err := f.WriteAt(buf, int64(size)); err != nil { 94 b.Fatal(err) 95 } 96 } 97 } 98 if err := f.Sync(); err != nil { 99 b.Fatal(err) 100 } 101 size = 0 102 b.StartTimer() 103 } 104 if _, err := f.WriteAt(buf, int64(size)); err != nil { 105 b.Fatal(err) 106 } 107 size += len(buf) 108 if size >= targetSize { 109 _ = f.Close() 110 f = nil 111 } 112 } 113 b.StopTimer() 114 }) 115 } 116 }