Go語言寫檔案幾種方式效能對比

2021-08-18 03:13:09 字數 1541 閱讀 5936

go語言中寫檔案有多種方式,這裡進行如下幾種方式的速度對比:

在vmware下的ubuntu 14.04下執行的結果表明:

測試**如下:

package main

import ( "fmt"

"os"

"time")

func benchmarkfilewrite(filename string, n int, index int) (d time.duration)

file.writestring(v)

file.writestring("\n")

file.close()

} case 1: // open file and write, defer close, repeat n times

for i := 0; i < n; i++

defer file.close()

file.writestring(v)

file.writestring("\n")

} case 2: // open file and write n times, then close file

fmt.println(index, "open file failed.", err.error()) break

}defer file.close() for i := 0; i < n; i++

}t1 := time.now()

d = t1.sub(t0)

fmt.printf("time of way(%d)=%v\n", index, d) return d

}func main() for i := 0; i < k; i++ for i := 0; i < k-1; i++

}

當n=1000時,測試結果如下

time of way(0)=38.719386ms

time of way(1)=31.428677ms

time of way(2)=17.930829ms

way 0 cost time is 2.2 times of way 2

way 1 cost time is 1.8 times of way 2

​​​​​​​當n=5000時,測試結果如下(因為方式1報錯,所以它的時間是錯的)

time of way(0)=170.003521ms  1 1021 open file failed. open benchmarkfile.txt: too many open files

time of way(1)=32.388994ms

time of way(2)=77.777936ms

way 0 cost time is 2.2 times of way 2

way 1 cost time is 0.4 times of way 2

​​​​​​​參考:

幾種IO讀檔案效能對比

檔案大小19m,10萬行左右的資料。堆記憶體設定如下 一,nio,無記憶體溢位,耗時220毫秒左右。缺點是實現起來太複雜,要考慮漢字等。package myweb.test.nio import j a.io.file import j a.io.fileinputstream import j a...

記憶體對映檔案效能對比測試

今天對比了一下記憶體對映檔案的效能和普通檔案的測試,不比不知道,一比嚇一跳啊。差距太大了。public class filetest long end system.currenttimemillis fc.close system.out.println end start catch excep...

go 寫檔案 go 寫檔案的方式

os.openfile openfile接收三個引數 檔名,檔案模式,許可權 以只寫方式開啟,並且追加寫入 os.create 底層還是呼叫了os.openfile,create 會建立乙個檔案,如果檔案已存在,會清空檔案,然後寫入。func main defer file.close n,err ...