fprintf vs std :: ofstream的非常令人惊讶的性能(fprintf非常慢) [英] Very surprising perfs of fprintf vs std::ofstream (fprintf is very slow)

查看:508
本文介绍了fprintf vs std :: ofstream的非常令人惊讶的性能(fprintf非常慢)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一些基准测试,以找到最有效的方法来用C ++向文件中写入巨大的数组(ASCII中超过1Go).

I was running some benchmarks to find the most efficient way to write a huge array to a file in C++ (more than 1Go in ASCII).

因此我将std :: ofstream与fprintf进行了比较(请参阅下面使用的开关)

So I compared std::ofstream with fprintf (see the switch I used below)

    case 0: {
        std::ofstream out(title, std::ios::out | std::ios::trunc);
        if (out) {
            ok = true;
            for (i=0; i<M; i++) {
                for (j=0; j<N; j++) {
                    out<<A[i][j]<<" ";
                }
                out<<"\n";
            }
            out.close();
        } else {
            std::cout<<"Error with file : "<<title<<"\n";
        }
        break;
    }
    case 1: {
        FILE *out = fopen(title.c_str(), "w");
        if (out!=NULL) {
            ok = true;
            for (i=0; i<M; i++) {
                for (j=0; j<N; j++) {
                    fprintf(out, "%d ", A[i][j]);
                }
                fprintf(out, "\n");
            }
            fclose(out);
        } else {
            std::cout<<"Error with file : "<<title<<"\n";
        }
        break;
    }

我的巨大问题是fprintf似乎比std :: ofstream慢了12倍.您是否知道我的代码中问题的根源是什么?还是与fprintf相比,std :: ofstream的优化程度更高?

And my huge problem is that fprintf seems to be more thant 12x slower compared to std::ofstream. Do you have an idea of what is the origin of the problem in my code ? Or maybe std::ofstream is very optimized compared to fprintf ?

(还有另一个问题:您知道写文件的另一种更快的方法)

(and an other question : do you know another faster way to write a file)

非常感谢您

(详细信息:我正在使用g ++ -Wall -O3进行编译)

(detail : I was compiling with g++ -Wall -O3)

推荐答案

fprintf("%d"要求格式字符串的运行时解析,每个整数一次. ostream& operator<<(ostream&, int)由编译器解析,每次编译一次.

fprintf("%d" requires runtime parsing of the format string, once per integer. ostream& operator<<(ostream&, int) is resolved by the compiler, once per compilation.

这篇关于fprintf vs std :: ofstream的非常令人惊讶的性能(fprintf非常慢)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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