我想加快CPU二進制搜索。不幸的是,GPU版本總是比CPU版本慢得多。也許問題不適合GPU或者我做錯了什麼?CUDA二進制搜索執行
CPU版本(約0.6ms):使用長度爲2000的排序後的數組和特定值做二進制搜索
...
Lookup (search[j], search_array, array_length, m);
...
int Lookup (int search, int* arr, int length, int& m)
{
int l(0), r(length-1);
while (l <= r)
{
m = (l+r)/2;
if (search < arr[m])
r = m-1;
else if (search > arr[m])
l = m+1;
else
{
return index[m];
}
}
if (arr[m] >= search)
return m;
return (m+1);
}
GPU版本 (約20毫秒): 使用長度2000的排序後的數組,並做二進制搜索具體價值
....
p_ary_search<<<16, 64>>>(search[j], array_length, dev_arr, dev_ret_val);
....
__global__ void p_ary_search(int search, int array_length, int *arr, int *ret_val)
{
const int num_threads = blockDim.x * gridDim.x;
const int thread = blockIdx.x * blockDim.x + threadIdx.x;
int set_size = array_length;
ret_val[0] = -1; // return value
ret_val[1] = 0; // offset
while(set_size != 0)
{
// Get the offset of the array, initially set to 0
int offset = ret_val[1];
// I think this is necessary in case a thread gets ahead, and resets offset before it's read
// This isn't necessary for the unit tests to pass, but I still like it here
__syncthreads();
// Get the next index to check
int index_to_check = get_index_to_check(thread, num_threads, set_size, offset);
// If the index is outside the bounds of the array then lets not check it
if (index_to_check < array_length)
{
// If the next index is outside the bounds of the array, then set it to maximum array size
int next_index_to_check = get_index_to_check(thread + 1, num_threads, set_size, offset);
if (next_index_to_check >= array_length)
{
next_index_to_check = array_length - 1;
}
// If we're at the mid section of the array reset the offset to this index
if (search > arr[index_to_check] && (search < arr[next_index_to_check]))
{
ret_val[1] = index_to_check;
}
else if (search == arr[index_to_check])
{
// Set the return var if we hit it
ret_val[0] = index_to_check;
}
}
// Since this is a p-ary search divide by our total threads to get the next set size
set_size = set_size/num_threads;
// Sync up so no threads jump ahead and get a bad offset
__syncthreads();
}
}
即使我嘗試更大的陣列,時間比例並沒有更好的。
簡單的二進制搜索並不完全適合GPU操作。這是一個無法並行化的串行操作。但是,您可以將數組拆分爲小塊,然後在每個塊上執行二進制搜索。創建X塊,確定哪些可能包含X並行線程中的變量。拋出所有,但候選人,進一步細分,等等... –
您可能想要檢查推測二進制搜索在http://wiki.thrust.googlecode.com/hg/html/group__binary__search.html – jmsu