There are several ways to write files in the go language, and there are several ways to speed comparisons:
- Open the file, write the content, close the file. Repeated so many times
- Open the file, write the content, defer close the file. Repeated so many times
- Open file, repeatedly write content, defer close file
The results of the operation under the Ubuntu 14.04 under VMware Show:
- Mode 1 is the slowest, but slow and stable.
- Mode 2 is slightly faster than the mode 1, but the number of repetitions will be error, it should be defer too much pressure stack so that the system can not support too many open files
- Mode 3 is about twice times faster than the previous two, because it reduces the number of open close files
The test code is as follows:
Package Mainimport ("FMT" "OS" " Time") func benchmarkfilewrite (filenamestringNint, indexint) (d time. Duration) {V:="ni shuo wo shi bu shi tai wu liao le a?"OS. Remove (filename) T0:=Time . Now ()SwitchIndex { Case 0://open File and write, then close, repeat n times forI: =0; I < n; i++{file, err:= OS. OpenFile (filename, os. O_wronly|os. O_append|os. O_create,0666) ifErr! =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 times forI: =0; I < n; i++{file, err:= OS. OpenFile (filename, os. O_wronly|os. O_append|os. O_create,0666) ifErr! =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) ifErr! =Nil {fmt. PRINTLN (Index,"Open file failed.", Err. Error ()) Break} defer file. Close () forI: =0; I < n; i++{file. WriteString (v) file. WriteString ("\ n")}} T1:=Time . Now () d=t1. Sub (t0) fmt. Printf ("Time of the (%d) =%v\n", index, D)returnD}func Main () {ConstK, Nint=3, +D:=[K]time. duration{} forI: =0; I < K; i++{D[i]= Benchmarkfilewrite ("BenchmarkFile.txt", N, i)} forI: =0; I < K1; i++{fmt. Printf ("The by-the-%6.1f time is %d\n", I, float32 (D[i])/float32 (d[k-1]), K-1) }}
When n=1000, the test results are as follows
Time of the (0) =719386ms time of the (1) =. 428677ms Time of the (2) =930829ms 0is 2.2 21is 1.8 2
When n=5000, the test result is as follows (because the error of mode 1, so its time is wrong)
Time of the-0)= the. 003521ms1 1021Open file failed. Open BenchmarkFile.txt:too Many open files time of the-1)= +. 388994ms Time (2)= the. 777936ms0Cost time is 2.2Times of the2 the1Cost time is 0.4Times of the2
Notes Go language Write file several ways performance comparison