TianZerL
TianZerL

Reputation: 135

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

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

Upvotes: 1

Views: 1079

Answers (1)

peterSO
peterSO

Reputation: 166825

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

Upvotes: 6

Related Questions