与C相比,为什么Go写入文件字节的速度较慢 [英] Why write bytes to files is slow for Go, compared with C

查看:63
本文介绍了与C相比,为什么Go写入文件字节的速度较慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚发现Go写入文件的字节很慢.

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

我想创建一个10mb的文件.Go需要大约1分钟的时间来完成,但是在C语言中不到5秒.

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

这是Go代码:

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")
}

和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;
}

推荐答案

无意义的微基准测试将产生毫无意义的结果.

Meaningless microbenchmarks produce meaningless results.

开始:

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")
}

输出:

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;
}

输出:

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

这篇关于与C相比,为什么Go写入文件字节的速度较慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆