我做了一個簡單的數組,其中包含2,000,000個整數,用於保存所有RGB,另一個數組保存2,000,000個整數,用於檢測rgb的次數。然後我把它通過所有600萬個字節的圖片,像這樣的循環:C#緩慢搜索
uint[] colors = new uint[rawImageBytes.Length/3];
int[] hits = new int[rawImageBytes.Length/3];
int colorAmount = 0;
int totalRepeats = 0;
int lastTime = Environment.TickCount;
int lastCount = 0;
uint currentColor = 0;
bool found;
for (int i = 0; i < rawImageBytes.Length - 3; i += 3)
{
if (Environment.TickCount - lastTime > 10000)
{
setStatus(((i - lastCount)/10) + " checks per second");
lastTime = Environment.TickCount;
lastCount = i;
}
currentColor = (uint)((rawImageBytes[i] << 0) | (rawImageBytes[i + 1] << 8) | (rawImageBytes[i + 2] << 16));
//set it to false to see if pattern exists
found = false;
//check all patterns
for (int k = 0; k < colorAmount; k++)
{
//if pattern exists
if (colors[k] == currentColor)
{
//dont add it and increase the hit instead
found = true;
hits[k]++;
}
}
//if pattern does not exist, set it
if (found == false)
{
colors[colorAmount] = currentColor;
hits[colorAmount] = 0;
colorAmount++;
}
}
我的日誌顯示,他們的速度從搜索範圍每秒
增加5724檢查顯著減慢每秒
5959檢查
5847檢查每秒
6044檢查每每秒鐘
11469檢查每秒
7096檢查第二
6318檢查每秒
8530檢查每秒
10680檢查每秒
16233檢查
如何使我的搜索更高效,以便不需要20分鐘?
二進制搜索不是特別快,因爲分支很難預測CPU。如果它比哈希慢很多,不要感到驚訝。 – usr 2012-03-18 13:08:22