Why write bytes to files is slow for Go, compared with C

时光总嘲笑我的痴心妄想 提交于 2021-02-07 04:17:13

问题


I just found that write bytes to files is slow for Go.

I want to create a 10mb file. Go takes almost 1 min to do it, but it is less than 5 seconds in C.

This is Go code:

package main

import (
    "fmt"
    "os"
)

func main() {
    f, _ := os.Create("./src/test/test.txt")
    count := int(1.024e7)
    for i := 0; i < count; i++ {
        f.Write([]byte{byte('a' + i%24)})
    }
    f.Close()
    fmt.Println("ok")
}

And C:

#include <stdio.h>

int main()
{
    FILE *fp=fopen("data.txt","w");
    int  size=1.024e7;
    for(int i=0;i<size;i++)
        putc('a'+i%24,fp);
    fclose(fp);
    printf("ok");
    return 0;
}

回答1:


Meaningless microbenchmarks produce meaningless results.


Go:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    f, _ := os.Create("tmp/sotest/test.txt")
    w := bufio.NewWriter(f)
    count := int(1.024e7)
    for i := 0; i < count; i++ {
        w.Write([]byte{byte('a' + i%24)})
    }
    w.Flush()
    f.Close()
    fmt.Println("ok")
}

Output:

ok
real    0m0.159s
user    0m0.160s
sys     0m0.004s

C:

#include <stdio.h>

int main()
{
    FILE *fp=fopen("data.txt","w");
    int  size=1.024e7;
    for(int i=0; i<size; i++)
        putc('a'+i%24,fp);
    fclose(fp);
    printf("ok");
    return 0;
}

Output:

ok
real    0m0.058s
user    0m0.045s
sys     0m0.004s


来源:https://stackoverflow.com/questions/59236310/why-write-bytes-to-files-is-slow-for-go-compared-with-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!