count_sort计数排序OpenMP的并行化
生活随笔
收集整理的這篇文章主要介紹了
count_sort计数排序OpenMP的并行化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
簡述
計數排序,就是統計某個數值在所有的數字中所應該存在的位置,然后,放到一個確定的位置上。非常簡單的排序算法。
程序
- 會讀取data.txt中的文件
- 數據的樣子
- 效果
- 代碼
和串行的計數排序進行對比
- 不要輸出排序結果,因為數據量太大了。
- 10000個數據的排序效果
- 接近9倍的速度(因為我在筆記本上有8個核)
- 后面多了一個r命令,其實是免得在vs編譯的時候被調用。隨便寫什么都是ok的。
和qsort的串行版也做對比
#include <iostream> #include <omp.h> #include <fstream> #include <ctime> using namespace std; #pragma warning(disable : 4996) int cmp(const void * a, const void *b) //from small to big {return *(int *)a - *(int *)b; }int main(int argc, char **argv) {if (argc < 2) return 0;ifstream cin("./data.txt");int i, j, count, n;cin >> n;int *a = new int[n];int *b = new int[n];int *c = new int[n];int *temp = new int[n];//int thread_count = strtol(argv[1], NULL, 10);for (i = 0; i < n; ++i) cin >> b[i];for (i = 0; i < n; ++i) { a[i] = b[i]; c[i] = b[i]; }clock_t starttime, endtime;starttime = clock();qsort(c, n, sizeof(int), cmp);endtime = clock();cout << "Total time Serial-qsort: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;starttime = clock();for (i = 0; i < n; ++i) {count = 0;for (j = 0; j < n; ++j) {if (b[j] < b[i]) count++;else if (b[j] == b[i] && j < i) count++;}temp[count] = b[i];}memcpy(b, temp, n * sizeof(int));endtime = clock();cout << "Total time Serial: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;starttime = clock(); #pragma omp parallel for private(i, j, count) shared(n, a, temp)for (i = 0; i < n; ++i) {count = 0;for (j = 0; j < n; ++j) {if (a[j] < a[i]) count++;else if (a[j] == a[i] && j < i) count++;}temp[count] = a[i];}#pragma omp parallel for for (i = 0; i < n; ++i) a[i] = temp[i];endtime = clock();//for (i = 0; i < n; ++i) cout << a[i]<< " ";//cout << endl;cout << "Total time parallel: " << (double)(endtime - starttime) / CLOCKS_PER_SEC << "s" << endl;delete[]temp;delete[]a; }總結
以上是生活随笔為你收集整理的count_sort计数排序OpenMP的并行化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梯形积分法【OpenMP实现】多个版本
- 下一篇: CUDA遇到在VS创建的项目运行报C10