github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zfile/memory_test.go (about)

     1  package zfile
     2  
     3  import (
     4  	"bufio"
     5  	"os"
     6  	"strconv"
     7  	"sync"
     8  	"testing"
     9  
    10  	"github.com/sohaha/zlsgo"
    11  )
    12  
    13  func TestMain(m *testing.M) {
    14  	m.Run()
    15  	_ = Remove("6.txt")
    16  	_ = Remove("7.txt")
    17  	_ = Remove("8.txt")
    18  	os.Exit(0)
    19  }
    20  
    21  func TestMemoryFile(t *testing.T) {
    22  	tt := zlsgo.NewTest(t)
    23  	f := NewMemoryFile("6.txt", MemoryFileAutoFlush(1), MemoryFileFlushBefore(func(f *MemoryFile) error {
    24  		f.SetName("7.txt")
    25  		t.Log(f.Size())
    26  		return nil
    27  	}))
    28  
    29  	t.Log(f.Name())
    30  	tt.EqualTrue(!f.IsDir())
    31  	t.Log(f.ModTime())
    32  	t.Log(f.Mode())
    33  	t.Log(f.Sys())
    34  	t.Log(f.Size())
    35  
    36  	var wg sync.WaitGroup
    37  	for i := 0; i < 1000; i++ {
    38  		wg.Add(1)
    39  		go func(i int) {
    40  			_, err := f.Write([]byte(strconv.Itoa(i) + "\n"))
    41  			wg.Done()
    42  			tt.NoError(err)
    43  		}(i)
    44  	}
    45  
    46  	b := []byte("--\n")
    47  	_, err := f.Write(b)
    48  	tt.NoError(err)
    49  	t.Log(len(f.Bytes()))
    50  	wg.Wait()
    51  	t.Log(len(f.Bytes()))
    52  	tt.NoError(f.Close())
    53  	t.Log(FileSize("7.txt"))
    54  	tt.NoError(f.Close())
    55  }
    56  
    57  func BenchmarkFileMem6(b *testing.B) {
    58  	name := "6.txt"
    59  	f := NewMemoryFile(name)
    60  	for i := 0; i < b.N; i++ {
    61  		_, err := f.Write([]byte(strconv.Itoa(i)))
    62  		if err != nil {
    63  			b.Fatal(err)
    64  		}
    65  	}
    66  	_ = WriteFile(name, f.Bytes())
    67  }
    68  
    69  func BenchmarkFileReal8(b *testing.B) {
    70  	name := "8.txt"
    71  	for i := 0; i < b.N; i++ {
    72  		err := WriteFile(name, []byte(strconv.Itoa(i)), true)
    73  		if err != nil {
    74  			b.Fatal(err)
    75  		}
    76  	}
    77  }
    78  
    79  func BenchmarkFileBufio7(b *testing.B) {
    80  	name := "7.txt"
    81  	file, _ := os.OpenFile(name, os.O_WRONLY|os.O_CREATE, 0766)
    82  	write := bufio.NewWriter(file)
    83  	for i := 0; i < b.N; i++ {
    84  		_, err := write.Write([]byte(strconv.Itoa(i)))
    85  		if err != nil {
    86  			b.Fatal(err)
    87  		}
    88  	}
    89  	write.Flush()
    90  }