非常令人惊讶的fprintf对比std :: ofstream(fprintf很慢)

Vin*_*ent 8 c++ printf ofstream

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

所以我将std :: ofstream与fprintf进行了比较(参见下面我使用的开关)

    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;
    }
Run Code Online (Sandbox Code Playgroud)

我的巨大问题是,与std :: ofstream相比,fprintf似乎要慢12倍.您是否知道我的代码中问题的根源是什么?或者也许std :: ofstream与fprintf相比是非常优化的?

(和另一个问题:你知道另一种更快的写文件方式)

非常感谢你

(细节:我用g ++ -Wall -O3编译)

MSa*_*ers 17

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