[笔记]Go语言写文件几种方式性能对比
生活随笔
收集整理的這篇文章主要介紹了
[笔记]Go语言写文件几种方式性能对比
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Go語言中寫文件有多種方式,這里進(jìn)行如下幾種方式的速度對(duì)比:
在VMWare下的Ubuntu 14.04下運(yùn)行的結(jié)果表明:
- 方式1速度最慢,但是慢的很穩(wěn)定
- 方式2比方式1略快,但是重復(fù)次數(shù)多了后會(huì)報(bào)錯(cuò),應(yīng)該是defer被壓棧太多導(dǎo)致系統(tǒng)撐不了太多打開的文件
- 方式3速度約是前兩者的2倍,因?yàn)闇p少了很多打開關(guān)閉文件的操作
測試代碼如下:
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)} }?
當(dāng)n=1000時(shí),測試結(jié)果如下
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?
當(dāng)n=5000時(shí),測試結(jié)果如下(因?yàn)榉绞?報(bào)錯(cuò),所以它的時(shí)間是錯(cuò)的)
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?
轉(zhuǎn)載于:https://www.cnblogs.com/journeyonmyway/p/4320987.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的[笔记]Go语言写文件几种方式性能对比的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【EasyPR】Linux安装使用Eas
- 下一篇: 大数据项目流程(必须会)