wordcount openmp并行 C/C++代码,打印运行时间并将统计结果保存至txt终
时间: 2024-01-21 10:19:33 浏览: 61
以下是使用OpenMP并行化的C++代码,实现对文本文件中单词数量的统计,并将运行时间和统计结果保存至txt文件:
```c++
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <omp.h>
using namespace std;
int main(int argc, char* argv[]) {
if (argc < 3) {
cout << "Usage: " << argv[0] << " input_file output_file" << endl;
return 1;
}
string input_file = argv[1];
string output_file = argv[2];
ifstream fin(input_file);
if (!fin) {
cout << "Failed to open file: " << input_file << endl;
return 1;
}
vector<string> words;
string line, word;
while (getline(fin, line)) {
stringstream ss(line);
while (ss >> word) {
words.push_back(word);
}
}
fin.close();
int num_words = words.size();
int num_threads = omp_get_max_threads();
int* word_counts = new int[num_threads]();
double start_time = omp_get_wtime();
#pragma omp parallel
{
int thread_id = omp_get_thread_num();
int start = (thread_id * num_words) / num_threads;
int end = ((thread_id + 1) * num_words) / num_threads;
int count = 0;
for (int i = start; i < end; i++) {
if (isalpha(words[i][0])) {
count++;
}
}
word_counts[thread_id] = count;
}
int total_count = 0;
for (int i = 0; i < num_threads; i++) {
total_count += word_counts[i];
}
double end_time = omp_get_wtime();
ofstream fout(output_file);
if (!fout) {
cout << "Failed to open file: " << output_file << endl;
return 1;
}
fout << "Number of words: " << num_words << endl;
fout << "Number of words starting with a letter: " << total_count << endl;
fout << "Execution time: " << (end_time - start_time) << " seconds" << endl;
fout.close();
delete[] word_counts;
return 0;
}
```
该程序使用OpenMP库实现并行化。它首先读取输入文件中的所有单词,并将它们存储在一个向量中。接下来,程序启动多个线程,在每个线程中,它将向量中的单词分配给线程处理。每个线程计算它所处理的单词中以字母开头的单词数,并将结果存储在一个数组中。最后,程序合并所有线程的结果,并将统计信息保存到输出文件中。
要编译该程序,请使用以下命令:
```
g++ -fopenmp wordcount.cpp -o wordcount
```
其中,`-fopenmp`选项启用OpenMP支持。
要运行该程序,请在命令行中指定输入文件和输出文件的路径,例如:
```
./wordcount input.txt output.txt
```
程序将读取`input.txt`中的单词,并将统计结果写入`output.txt`中。