go和python讀寫文件的效率對比

對比項目

單線程順序執(zhí)行程序,在本地磁盤對文件進行讀和寫。

寫文件

執(zhí)行步驟:

  1. 向本地磁盤寫1千萬行文本。
  2. 記錄寫完的時間。

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百萬行數(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))
}

最后會在磁盤生成一個9.7GB的文本文件。
耗時:

  • python:48s
  • go: 27s

讀文件

執(zhí)行步驟:

  1. 讀取前面寫入的9.7GB的文本文件。
  2. 記錄遍歷完每一行所需要的時間。

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í)行時間:

  • python:42s
  • go:27s

總結(jié)

在最簡單的文件IO層面,go語言已經(jīng)在性能上對python展現(xiàn)出了壓倒性的優(yōu)勢,更不用說go的更厲害的goroutine高并發(fā)的特性了。


image.png

但是python的優(yōu)勢就是語法簡潔,代碼量少。

所以:如果要看程序執(zhí)行效率,還是用go。如果是和人比效率,追求自動化,建議用python。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容