對(duì)比項(xiàng)目
單線程順序執(zhí)行程序,在本地磁盤對(duì)文件進(jìn)行讀和寫屿愚。
寫文件
執(zhí)行步驟:
- 向本地磁盤寫1千萬(wàn)行文本。
- 記錄寫完的時(shí)間艘希。
python腳本
import os
import time
file=open("temp-py.txt",'w')
sTime=time.time()
for i in range(int(round(1e8))):#
file.write("helllo worldhelllo worldhelllo worldhelllo worldhelllo worldhelllo worldhelllo worldhelllo world\n")
file.close()
print("cost time:%d/s"%(time.time()-sTime))
go程序
package main
import (
"bufio"
"flag"
"log"
"os"
"time"
)
func main() {
var filePath string
flag.StringVar(&filePath, "f", "", "-f=path/to/your/filePath")
flag.Parse()
if filePath == "" {
filePath = os.Getenv("HOME") + "/temp-go.txt"
}
file, _ := os.Create(filePath)
defer file.Close()
wt := bufio.NewWriter(file)
//寫入1百萬(wàn)行數(shù)據(jù)八秃,11s
sTime := time.Now().UnixNano() / 1e6
for i := 0; i < 1e8; i++ {
_, err := wt.WriteString("helllo worldhelllo worldhelllo worldhelllo worldhelllo worldhelllo worldhelllo worldhelllo world\n")
if err != nil {
log.Println(err)
}
}
wt.Flush()
eTime := time.Now().UnixNano() / 1e6
log.Printf("cost time:%d/ms", (eTime - sTime))
}
最后會(huì)在磁盤生成一個(gè)9.7GB的文本文件机隙。
耗時(shí):
- python:48s
- go: 27s
讀文件
執(zhí)行步驟:
- 讀取前面寫入的9.7GB的文本文件臼隔。
- 記錄遍歷完每一行所需要的時(shí)間寥假。
Python腳本
import os
import time
file=open("temp-go.txt",'r')
sTime=time.time()
while file.readline():#
pass
file.close()
print("cost time:%d/s"%(time.time()-sTime))
go程序
package main
import (
"bufio"
"log"
"os"
"time"
)
func main() {
filePath := os.Getenv("HOME") + "/temp-go.txt"
file, _ := os.Open(filePath)
sTime := time.Now().Unix()
myscan := bufio.NewScanner(file)
for myscan.Scan() {
}
eTime := time.Now().Unix()
log.Fatalf("cost time:%d/s", (eTime - sTime))
}
執(zhí)行時(shí)間:
- python:42s
- go:27s
總結(jié)
在最簡(jiǎn)單的文件IO層面,go語(yǔ)言已經(jīng)在性能上對(duì)python展現(xiàn)出了壓倒性的優(yōu)勢(shì)疗隶,更不用說(shuō)go的更厲害的goroutine高并發(fā)的特性了佑笋。
image.png
但是python的優(yōu)勢(shì)就是語(yǔ)法簡(jiǎn)潔,代碼量少斑鼻。
所以:如果要看程序執(zhí)行效率蒋纬,還是用go。如果是和人比效率坚弱,追求自動(dòng)化颠锉,建議用python。