C++ 对TXT 的串并行读写
生活随笔
收集整理的這篇文章主要介紹了
C++ 对TXT 的串并行读写
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
任務(wù)說明:有36篇文檔,現(xiàn)在要讀入,并統(tǒng)計(jì)詞頻,字典長度25,希望能夠比較串并行讀寫操作的時(shí)間差距。
?
針對第一種思路,使用openmp做多線程處理:
// LoadDocsByOpenMP.cpp // #include <omp.h> #include <iostream> #include <stdio.h> #include <vector> #include <stdlib.h> #include <time.h> #include <string> using namespace std;int main() {char filename[100],resultname[100];int d;FILE *fileptr[360];int word;int ff[360][25] = { 0 };//vector< vector<int> > corpus;clock_t start,finish;int f[360]={0};start=clock();printf("load data ...\n"); #pragma omp parallel for num_threads(4)for (d = 1; d < 361; d++){printf("Hello world, I am %d, docs index %d.\n",omp_get_thread_num(),d);sprintf(filename, "..//data/doc_%d.txt", d);fileptr[d-1] = fopen(filename, "r");//int ff[25]={0};vector<int> doc;while (fscanf(fileptr[d-1], "%d", &word) != EOF){ff[d-1][word - 1] = ff[d-1][word - 1] + 1;//ff[word-1]=ff[word-1]+1;// //doc.push_back(word);}corpus.push_back(doc);fclose(fileptr[d-1]);sprintf(resultname, "..//result/freqByOpenMP_%d.txt", d);//Be CAREFUL!For the name "filename" has been used before, we must name the string differently here.fileptr[d-1] = fopen(resultname, "w");for (f[d-1] = 0; f[d-1] < 25; f[d-1]++){fprintf(fileptr[d-1], "%d ", ff[f[d-1]]);}fclose(fileptr[d-1]);}//cout <<"corpus.size()="<< corpus.size() << endl;finish=clock();cout<<"time cost : "<< (double)(finish-start)/ CLOCKS_PER_SEC<<endl;return 0; }
?但初步比較openmp對串行讀取的速度并沒有太多提升,反而是當(dāng)進(jìn)程數(shù)多于系統(tǒng)物理核數(shù)的時(shí)候,程序時(shí)間會加長。
另外兩種實(shí)現(xiàn)思路在后續(xù)學(xué)習(xí)中繼續(xù)實(shí)現(xiàn)。
轉(zhuǎn)載于:https://www.cnblogs.com/simayuhe/p/7208393.html
總結(jié)
以上是生活随笔為你收集整理的C++ 对TXT 的串并行读写的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 重载,重写及数组练习
- 下一篇: Codeforces Round #42