日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

[笔记]Go语言写文件几种方式性能对比

發布時間:2023/12/20 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [笔记]Go语言写文件几种方式性能对比 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Go語言中寫文件有多種方式,這里進行如下幾種方式的速度對比:

  • 打開文件,寫入內容,關閉文件。如此重復多次
  • 打開文件,寫入內容,defer 關閉文件。如此重復多次
  • 打開文件,重復多次寫入內容,defer 關閉文件
  • 在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语言写文件几种方式性能对比的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。