用C ++编写一个二进制文件非常快 [英] Writing a binary file in C++ very fast

查看:151
本文介绍了用C ++编写一个二进制文件非常快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的SSD(固态驱动器)上写入大量的数据。

I'm trying to write huge amounts of data onto my SSD(solid state drive). And by huge amounts I mean 80GB.

我浏览网页的解决方案,但我想出的最好的是:

I browsed the web for solutions, but the best I came up with was this:

#include <fstream>
using namespace std;
const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    fstream myfile;
    myfile = fstream("file.binary", ios::out | ios::binary);
    //Here would be some error handling
    for(int i = 0; i < 32; ++i){
        //Some calculations to fill a[]
        myfile.write((char*)&a,size*sizeof(unsigned long long));
    }
    myfile.close();
}

使用Visual Studio 2010和完整优化编译并在Windows7下运行此程序约20MB / s。真正让我困扰的是,Windows可以将文件从其他SSD到这个SSD在150MB / s和200MB / s之间的某个位置。所以至少7倍更快。

Compiled with Visual Studio 2010 and full optimizations and run under Windows7 this program maxes out around 20MB/s. What really bothers me is that Windows can copy files from an other SSD to this SSD at somewhere between 150MB/s and 200MB/s. So at least 7 times faster. That's why I think I should be able to go faster.

任何想法如何加速我的写作?

Any ideas how I can speed up my writing?

推荐答案

这样做了:

#include <stdio.h>
const unsigned long long size = 8ULL*1024ULL*1024ULL;
unsigned long long a[size];

int main()
{
    FILE* pFile;
    pFile = fopen("file.binary", "wb");
    for (unsigned long long j = 0; j < 1024; ++j){
        //Some calculations to fill a[]
        fwrite(a, 1, size*sizeof(unsigned long long), pFile);
    }
    fclose(pFile);
    return 0;
}

我只是在36秒内定时8GB,约为220MB /这使我的SSD。还值得注意,我的帖子开头的代码使用一个核心100%,而此代码只使用2-5%。

I just timed 8GB in 36sec, which is about 220MB/s and I think that maxes out my SSD. Also worth to note, the code at the beginning of my post used one core 100%, whereas this code only uses 2-5%.

非常感谢大家。

这篇关于用C ++编写一个二进制文件非常快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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