[笔记]Go语言写文件几种方式性能对比
生活随笔
收集整理的這篇文章主要介紹了
[笔记]Go语言写文件几种方式性能对比
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Go語言中寫文件有多種方式,這里進行如下幾種方式的速度對比:
在VMWare下的Ubuntu 14.04下運行的結果表明:
- 方式1速度最慢,但是慢的很穩定
- 方式2比方式1略快,但是重復次數多了后會報錯,應該是defer被壓棧太多導致系統撐不了太多打開的文件
- 方式3速度約是前兩者的2倍,因為減少了很多打開關閉文件的操作
測試代碼如下:
package mainimport ("fmt""os""time" )func benchmarkFileWrite(filename string, n int, index int) (d time.Duration) {v := "ni shuo wo shi bu shi tai wu liao le a?"os.Remove(filename)t0 := time.Now()switch index {case 0: // open file and write, then close, repeat n timesfor i := 0; i < n; i++ {file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)if err != nil {fmt.Println(index, i, "open file failed.", err.Error())break}file.WriteString(v)file.WriteString("\n")file.Close()}case 1: // open file and write, defer close, repeat n timesfor i := 0; i < n; i++ {file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)if err != nil {fmt.Println(index, i, "open file failed.", err.Error())break}defer file.Close()file.WriteString(v)file.WriteString("\n")}case 2: // open file and write n times, then close filefile, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)if err != nil {fmt.Println(index, "open file failed.", err.Error())break}defer file.Close()for i := 0; i < n; i++ {file.WriteString(v)file.WriteString("\n")}}t1 := time.Now()d = t1.Sub(t0)fmt.Printf("time of way(%d)=%v\n", index, d)return d }func main() {const k, n int = 3, 1000d := [k]time.Duration{}for i := 0; i < k; i++ {d[i] = benchmarkFileWrite("benchmarkFile.txt", n, i)}for i := 0; i < k-1; i++ {fmt.Printf("way %d cost time is %6.1f times of way %d\n", i, float32(d[i])/float32(d[k-1]), k-1)} }?
當n=1000時,測試結果如下
time of way(0)=38.719386mstime of way(1)=31.428677mstime of way(2)=17.930829msway 0 cost time is 2.2 times of way 2way 1 cost time is 1.8 times of way 2?
當n=5000時,測試結果如下(因為方式1報錯,所以它的時間是錯的)
time of way(0)=170.003521ms1 1021 open file failed. open benchmarkFile.txt: too many open filestime of way(1)=32.388994mstime of way(2)=77.777936msway 0 cost time is 2.2 times of way 2way 1 cost time is 0.4 times of way 2?
轉載于:https://www.cnblogs.com/journeyonmyway/p/4320987.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的[笔记]Go语言写文件几种方式性能对比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【EasyPR】Linux安装使用Eas
- 下一篇: 大数据项目流程(必须会)