User Tools

Site Tools


Table of Contents

,

Writers Bench

Both examples write 1G of data.

FreeBSD, ZFS, SSD

  • clang, stream, -O1 - 1.002s
  • golang, bufio - 2.003s

Linux, ext4, SSD

  • g++, stream, -O1 - 2.400
  • golang, bufio - 1.028

WTF?

cpp

writer01.cpp
/*
 * Copyright Oleg Borodin  <borodin@unix7.org>
 */
 
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <chrono>
 
using namespace std::chrono;
using namespace std;
 
const string get_random_string(const int len) {
    string result;
    const char letters[] =
        "0123456789"
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        "abcdefghijklmnopqrstuvwxyz";
 
    for (auto n = 0; n < len; n++) {
        auto i = rand() % (sizeof(letters) - 1);
        result += letters[i];
    }
    return result;
}
 
int main(int argc, char **argv) {
    srand(time(0));
    auto data = get_random_string(1024);
 
    auto start = high_resolution_clock::now();
 
    //ofstream file("tmp.dat", ofstream::binary | ios_base::app);
    ofstream file("tmp-cpp.dat", ofstream::binary);
 
    //file.seekp(ios_base::beg);
    for (auto i = 0; i < 1024 * 1024; i++) {
        file << data;
    }
 
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
 
    cout << duration.count() << endl;
 
    file.flush();
    file.close();
    return 0;
 
}
//EOF

golang

writer01.go
/*
 * Copyright Oleg Borodin  <borodin@unix7.org>
 */
 
package main
 
import (
    "bufio"
    "os"
    "fmt"
    "math/rand"
    "time"
)
 
func randString(n int) string {
    const letters = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    arr := make([]byte, n)
    for i := range arr {
        arr[i] = letters[rand.Intn(len(letters))]
    }
    return string(arr)
}
 
const blockSize int = 1024
 
func main() {
    var err error
    file, err := os.Create("tmp-go.dat")
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    //defer file.Sync()
    defer file.Close()
 
    buffer := bufio.NewWriter(file)
 
    data := []byte(randString(blockSize))
 
    start := time.Now()
    for i := 0; i < 1024 * 1024; i++ {
        _, err := buffer.Write(data)
        if err != nil {
            fmt.Println(err)
            os.Exit(1)
        }
    }
    elapsed := time.Since(start)
    fmt.Println(elapsed)
}
//EOF