[英]C++ save and load huge vector<bool>
我有一個巨大的vector<vector<bool>>
(512x 44,000,000位)。 創建它需要花費4-5個小時來進行計算,顯然我想保存結果,以免我再次重復該過程。 當我再次運行該程序時,我要做的就是加載相同的向量(沒有其他應用程序將使用此文件)。
我相信文本文件對於這么大的尺寸是不可能的。 有沒有簡單(快速又臟)的方法來做到這一點? 我不使用Boost,這只是我的科學應用程序的一小部分,因此必須快速。 我還考慮過將其在線反轉並存儲在Postgres DB中(44000000條記錄和512位數據),因此DB可以輕松處理它。 我看到這樣的答案需要8bits> 1byte然后保存,但是由於我有限的新手C ++經驗,它們聽起來太復雜了。 有任何想法嗎?
您可以將 8位保存為一個字節:
unsigned char saver(bool bits[])
{
unsigned char output=0;
for(int i=0;i<8;i++)
{
output=output|(bits[i]<<i); //probably faster than if(){output|=(1<<i);}
//example: for the starting array 00000000
//first iteration sets: 00000001 only if bits[0] is true
//second sets: 0000001x only if bits[1] is true
//third sets: 000001xx only third is true
//fifth: 00000xxx if fifth is false
// x is the value before
}
return output;
}
您可以從單個字節加載 8位:
void loader(unsigned char var, bool * bits)
{
for(int i=0;i<8;i++)
{
bits[i] = var & (1 << i);
// for example you loaded var as "200" which is 11001000 in binary
// 11001000 --> zeroth iteration gets false
// first gets false
// second false
// third gets true
//...
}
}
1<<0 is 1 -----> 00000001
1<<1 is 2 -----> 00000010
1<<2 is 4 -----> 00000100
1<<3 is 8 -----> 00001000
1<<4 is 16 ----> 00010000
1<<5 is 32 ----> 00100000
1<<6 is 64 ----> 01000000
1<<7 is 128 ---> 10000000
編輯:使用gpgpu,在cpu上花費4-5個小時的令人尷尬的並行算法可以縮短為在gpu上的0.04-0.05個小時(甚至在使用多個gpu的情況下甚至不到一分鍾)。例如,上方的“ saver / loader”功能令人尷尬平行。
我看到這樣的答案需要8bits> 1byte然后保存,但是由於我有限的新手C ++經驗,它們聽起來太復雜了。 有任何想法嗎?
如果您要經常讀取文件,那么這是學習按位操作的好時機。 每布爾使用一位將是大小的1/8。 這樣可以節省大量內存和I / O。
因此,將其保存為每bool一位,然后將其分成大塊和/或使用映射的內存(例如mmap
)讀取。 您可以將其放在一個可用的接口后面,因此您只需執行一次即可,並在需要讀取值時抽象化序列化的格式。
如前所述,vec是bool向量的向量,我們將8 x 8子向量中的所有位打包成字節,然后將這些字節推入向量中。
std::vector<unsigned char> buf;
int cmp = 0;
unsigned char output=0;
FILE* of = fopen("out.bin")
for_each ( auto& subvec in vec)
{
for_each ( auto b in subvec)
{
output=output | ((b ? 1 : 0) << cmp);
cmp++;
if(cmp==8)
{
buf.push_back(output);
cmp = 0;
output = 0;
}
}
fwrite(&buf[0], 1, buf.size(), of);
buf.clear();
}
fclose(of);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.