write_files.go 1019 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "math/rand"
  6. "os"
  7. "time"
  8. )
  9. var (
  10. minSize = flag.Int("minSize", 1024, "min file size")
  11. maxSize = flag.Int("maxSize", 3*1024*1024, "max file size")
  12. fileCount = flag.Int("n", 1, "number of files to write")
  13. blockSize = flag.Int("blockSizeKB", 4, "write block size")
  14. toDir = flag.String("dir", ".", "destination directory")
  15. )
  16. func check(e error) {
  17. if e != nil {
  18. panic(e)
  19. }
  20. }
  21. func main() {
  22. flag.Parse()
  23. block := make([]byte, *blockSize*1024)
  24. for i := 0; i < *fileCount; i++ {
  25. f, err := os.Create(fmt.Sprintf("%s/file%05d", *toDir, i))
  26. check(err)
  27. fileSize := *minSize + rand.Intn(*maxSize-*minSize)
  28. startTime := time.Now()
  29. fmt.Printf("write %s %d bytes: ", f.Name(), fileSize)
  30. for x := 0; x < fileSize; {
  31. rand.Read(block)
  32. _, err = f.Write(block)
  33. check(err)
  34. x += len(block)
  35. }
  36. err = f.Close()
  37. check(err)
  38. fmt.Printf("%.02f MB/sec\n", float64(fileSize)*float64(time.Second)/float64(time.Now().Sub(startTime)*1024*1024))
  39. }
  40. }