我正试图将大量的数据写入我的SSD(固态硬盘)。我说的巨大是指80GB。
我在网上寻找解决方案,但我想到的最好的办法是:
#include <fstream>
const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
std::fstream myfile;
myfile = std::fstream("file.binary", std::ios::out | std::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可以以150MB/s到200MB/s之间的速度将文件从另一个SSD复制到这个SSD。至少快7倍。这就是为什么我认为我应该能跑得更快。
有什么办法可以加快我的写作速度吗?
您是否可以使用FILE*来代替,并衡量您所获得的性能?
有几个选项是使用fwrite/write而不是fstream:
#include <stdio.h>
int main ()
{
FILE * pFile;
char buffer[] = { 'x' , 'y' , 'z' };
pFile = fopen ( "myfile.bin" , "w+b" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fclose (pFile);
return 0;
}
如果你决定使用write,试试类似的方法:
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);
if (filedesc < 0) {
return -1;
}
if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
write(2, "There was an error writing to testfile.txt\n", 43);
return -1;
}
return 0;
}
我还建议你研究一下内存映射。这可能就是你的答案。有一次我不得不处理一个20GB的文件,把它存储在数据库中,而这个文件甚至没有打开。因此,解决方案是利用内存映射。不过我在Python中做到了。
您是否可以使用FILE*来代替,并衡量您所获得的性能?
有几个选项是使用fwrite/write而不是fstream:
#include <stdio.h>
int main ()
{
FILE * pFile;
char buffer[] = { 'x' , 'y' , 'z' };
pFile = fopen ( "myfile.bin" , "w+b" );
fwrite (buffer , 1 , sizeof(buffer) , pFile );
fclose (pFile);
return 0;
}
如果你决定使用write,试试类似的方法:
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int filedesc = open("testfile.txt", O_WRONLY | O_APPEND);
if (filedesc < 0) {
return -1;
}
if (write(filedesc, "This will be output to testfile.txt\n", 36) != 36) {
write(2, "There was an error writing to testfile.txt\n", 43);
return -1;
}
return 0;
}
我还建议你研究一下内存映射。这可能就是你的答案。有一次我不得不处理一个20GB的文件,把它存储在数据库中,而这个文件甚至没有打开。因此,解决方案是利用内存映射。不过我在Python中做到了。