日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

C++ 对TXT 的串并行读写

發(fā)布時(shí)間:2025/4/14 c/c++ 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C++ 对TXT 的串并行读写 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

任務(wù)說明:有36篇文檔,現(xiàn)在要讀入,并統(tǒng)計(jì)詞頻,字典長度25,希望能夠比較串并行讀寫操作的時(shí)間差距。

  • 串行讀入并統(tǒng)計(jì)詞頻 // LoadDocsInUbuntu.cpp//#include <iostream>#include <stdio.h>#include <vector>using namespace std;int main(){char filename[100];size_t d;FILE *fileptr;int word;vector< vector<int> > corpus;printf("load data ...\n");for (d = 1; d < 37; d++){sprintf(filename, "..//data/doc_%d.txt", d);fileptr = fopen(filename, "r");vector<int> doc;int ff[25] = { 0 };while (fscanf(fileptr, "%d", &word) != EOF){ff[word - 1] = ff[word - 1] + 1;doc.push_back(word);}corpus.push_back(doc);fclose(fileptr);sprintf(filename, "..//result/freqUbuntuSerial_%d.txt", d);fileptr = fopen(filename, "w");for (int f = 0; f < 25; f++){ fprintf(fileptr, "%d ", ff[f]);}fclose(fileptr);}cout <<"corpus.size()="<< corpus.size() << endl;return 0;}

    ?

  • 這里討論并行有三種思路:一,按照文檔序號進(jìn)行分組讀入統(tǒng)計(jì)等操作;二,在文檔內(nèi)按單詞數(shù)目分組進(jìn)行統(tǒng)計(jì);三,將統(tǒng)計(jì)與讀寫操作并行處理。

    針對第一種思路,使用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)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。