[英]Easy. Fast way to compare two 800k each elements arrays
使用mt19937_64生成器,我生成了800 000個從0到30000000范圍內的整數。每個數字都必須是唯一的,因此我應該將其與每個已經生成的整數進行比較:
unsigned array[800 000];
for (int i = 0; i < 800 000; i++)
{
generate_again:
buffer = uid(rng); // generate in buffer
for (int j = 0; j < i; j++) // *comparing to every already generated integer
{
if (buffer == array[j])
goto generate_again; // if the same integer exist, go togenerate_again flag
}
array[i] = pepper; // is integer is unique - it goes to array.
}
比較過程大約需要16分鍾。 我怎樣才能更快地完成? 謝謝。
您可以先按順序生成唯一編號,然后對它們進行混洗以獲得最終結果(如果需要的話)。
如果值已經生成,則使用std::bitset
將是一種有效的存儲方式。 另外,如果您實際上在編譯時不知道值的數量,則可以使用std::vector<bool>
,這是一種使用位操作的專門技術,它還可以節省一些空間。
#include <iostream>
#include <vector>
#include <algorithm>
#include <random>
#include <bitset>
int main()
{
static constexpr int max_value = 30'000'000;
static constexpr int n_values = 800'000;
std::bitset<max_value + 1> have_num;
int cur_n_values = 0;
std::mt19937_64 mt{std::random_device{}()};
std::uniform_int_distribution<int> distribution{0, max_value};
while (cur_n_values != n_values) {
auto newVal = distribution(mt);
if (!have_num[newVal]) {
have_num[newVal] = true;
++cur_n_values;
}
}
std::vector<int> nums;
nums.reserve(n_values);
for (int i = 0; i < have_num.size(); ++i) {
if (have_num[i]) {
nums.push_back(i);
}
}
std::shuffle(nums.begin(), nums.end(), mt);
for (auto i : nums) {
std::cout << i << " ";
}
}
如果不需要生成數組,請檢查唯一性並刪除元素-僅存儲唯一的數字。
嘗試使用hashed_unique
boost :: multiindex 。 如果要保留訂單,請使用ordered_unique
。
另請參見: 此
首先,通過遍歷數組消除檢查。 如果您只有30E6變體,則如果有足夠的空間,可以嘗試將它們放入一組布爾標志。 那將花費大約30Mb。 內存的另一種優化可能是將標志打包到位掩碼。 這將節省8倍的成本。 它將提高速度。 因此,如果具有大小為30Mb / 8(〜4Mb)的標志數組,則可以在恆定時間內檢查是否已生成數字。 這將大大提高速度。 但是還有另一個問題:擁有很多世代,您將陷入反復的碰撞中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.