golang的写文件测试

package main
 
import (
    "os"
    "strings"
    "time"
    "fmt"
    "strconv"
)    


//耗时统计函数
func timeCost() func() {
    start := time.Now()
    return func() {
        tc := time.Since(start)
        fmt.Printf("time cost = %v\n", tc)
    }
}

func sum(n int, fd *os.File)  {
    defer timeCost()()        //注意,是对 timeCost()返回的函数进行调用,因此需要加两对小括号

    for i:=1; i <= n; i++ {
        stri := strconv.Itoa(i)
           content := "写入的文件内容" + stri
        fd_time := time.Now().Format("2006-01-02 15:04:05")
        fd_content := strings.Join([]string{"======",fd_time,"=====",content,"\n"},"")
        buf := []byte(fd_content)
          fd.Write(buf)
  }
}

func main() {
    fd , _ := os.OpenFile("xyz2.txt",os.O_RDWR|os.O_CREATE|os.O_APPEND,0644)
    sum(10000,fd)
    fd.Close()
}

压测1w条记录,append追加写文件的耗费时间. 

 

你可能感兴趣的:(golang的写文件测试)