| 1 |
// Copyright (C) 2023 The Qt Company Ltd. |
| 2 |
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause |
| 3 |
|
| 4 |
#include <QtWidgets/qfiledialog.h> |
| 5 |
#include <QtWidgets/qapplication.h> |
| 6 |
#include <QtCore/qdebug.h> |
| 7 |
#include <QtCore/qmimedatabase.h> |
| 8 |
#include <QtCore/qelapsedtimer.h> |
| 9 |
#include <QtConcurrent/qtconcurrentmap.h> |
| 10 |
#include <QtCore/qtextstream.h> |
| 11 |
|
| 12 |
typedef QMap<QString, int> WordCount; |
| 13 |
|
| 14 |
void printHighestResult(const WordCount &, qsizetype); |
| 15 |
QStringList findFiles(const QString &); |
| 16 |
|
| 17 |
// Single threaded word counter function. |
| 18 |
WordCount singleThreadedWordCount(const QStringList &files) |
| 19 |
{ |
| 20 |
WordCount wordCount; |
| 21 |
for (const QString &file : files) { |
| 22 |
QFile f(file); |
| 23 |
if (!f.open(QIODevice::ReadOnly)) { |
| 24 |
qWarning().noquote() << "Failed to open file:" << QDir::toNativeSeparators(file) |
| 25 |
<< ":" << f.errorString(); |
| 26 |
return {}; |
| 27 |
} |
| 28 |
QTextStream textStream(&f); |
| 29 |
while (!textStream.atEnd()) { |
| 30 |
const auto words = textStream.readLine().split(' ', Qt::SkipEmptyParts); |
| 31 |
for (const QString &word : words) |
| 32 |
wordCount[word] += 1; |
| 33 |
} |
| 34 |
} |
| 35 |
return wordCount; |
| 36 |
} |
| 37 |
|
| 38 |
// countWords counts the words in a single file. This function is |
| 39 |
// called in parallel by several threads and must be thread |
| 40 |
// safe. |
| 41 |
WordCount countWords(const QString &file) |
| 42 |
{ |
| 43 |
QFile f(file); |
| 44 |
if (!f.open(QIODevice::ReadOnly)) { |
| 45 |
qWarning().noquote() << "Failed to open file:" << QDir::toNativeSeparators(file) |
| 46 |
<< ":" << f.errorString(); |
| 47 |
return {}; |
| 48 |
} |
| 49 |
QTextStream textStream(&f); |
| 50 |
WordCount wordCount; |
| 51 |
|
| 52 |
while (!textStream.atEnd()) { |
| 53 |
const auto words = textStream.readLine().split(' ', Qt::SkipEmptyParts); |
| 54 |
for (const QString &word : words) |
| 55 |
wordCount[word] += 1; |
| 56 |
} |
| 57 |
|
| 58 |
return wordCount; |
| 59 |
} |
| 60 |
|
| 61 |
// reduce adds the results from map to the final |
| 62 |
// result. This functor will only be called by one thread |
| 63 |
// at a time. |
| 64 |
void reduce(WordCount &result, const WordCount &w) |
| 65 |
{ |
| 66 |
for (auto i = w.begin(), end = w.end(); i != end; ++i) |
| 67 |
result[i.key()] += i.value(); |
| 68 |
} |
| 69 |
|
| 70 |
int main(int argc, char** argv) |
| 71 |
{ |
| 72 |
QApplication app(argc, argv); |
| 73 |
app.setOrganizationName("QtProject"); |
| 74 |
app.setApplicationName(QCoreApplication::translate("main", "Word Count")); |
| 75 |
|
| 76 |
QFileDialog fileDialog; |
| 77 |
fileDialog.setOption(QFileDialog::ReadOnly); |
| 78 |
// Grab the directory path from the dialog |
| 79 |
auto dirPath = QFileDialog::getExistingDirectory(nullptr, |
| 80 |
QCoreApplication::translate("main","Select a Folder"), |
| 81 |
QDir::currentPath()); |
| 82 |
|
| 83 |
QStringList files = findFiles(dirPath); |
| 84 |
qDebug() << QCoreApplication::translate("main", "Indexing %1 files in %2") |
| 85 |
.arg(files.size()).arg(dirPath); |
| 86 |
|
| 87 |
// Start the single threaded operation |
| 88 |
qint64 singleThreadTime; |
| 89 |
{ |
| 90 |
QElapsedTimer timer; |
| 91 |
timer.start(); |
| 92 |
//! [1] |
| 93 |
WordCount total = singleThreadedWordCount(files); |
| 94 |
//! [1] |
| 95 |
singleThreadTime = timer.elapsed(); |
| 96 |
qDebug() << QCoreApplication::translate("main", "Single threaded scanning took %1 ms") |
| 97 |
.arg(singleThreadTime); |
| 98 |
} |
| 99 |
// Start the multithreaded mappedReduced operation. |
| 100 |
qint64 mapReduceTime; |
| 101 |
{ |
| 102 |
QElapsedTimer timer; |
| 103 |
timer.start(); |
| 104 |
//! [2] |
| 105 |
WordCount total = QtConcurrent::mappedReduced(files, countWords, reduce).result(); |
| 106 |
//! [2] |
| 107 |
mapReduceTime = timer.elapsed(); |
| 108 |
qDebug() << QCoreApplication::translate("main", "MapReduce scanning took %1 ms") |
| 109 |
.arg(mapReduceTime); |
| 110 |
qDebug() << QCoreApplication::translate("main", "MapReduce speedup: %1") |
| 111 |
.arg(((double)singleThreadTime - (double)mapReduceTime) / (double)mapReduceTime + 1); |
| 112 |
printHighestResult(total, 10); |
| 113 |
} |
| 114 |
} |
| 115 |
|
| 116 |
// Utility function that recursively searches for text files. |
| 117 |
QStringList findFiles(const QString &startDir) |
| 118 |
{ |
| 119 |
QStringList names; |
| 120 |
QDir dir(startDir); |
| 121 |
static const QMimeDatabase db; |
| 122 |
|
| 123 |
const auto files = dir.entryList(QDir::Files); |
| 124 |
for (const QString &file : files) { |
| 125 |
const auto path = startDir + QDir::separator() + file; |
| 126 |
const QMimeType mime = db.mimeTypeForFile(QFileInfo(path)); |
| 127 |
const auto mimeTypesForFile = mime.parentMimeTypes(); |
| 128 |
|
| 129 |
for (const auto &i : mimeTypesForFile) { |
| 130 |
if (i.contains("text", Qt::CaseInsensitive) |
| 131 |
|| mime.comment().contains("text", Qt::CaseInsensitive)) { |
| 132 |
names += startDir + QDir::separator() + file; |
| 133 |
} |
| 134 |
} |
| 135 |
} |
| 136 |
|
| 137 |
const auto subdirs = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot); |
| 138 |
for (const QString &subdir : subdirs) { |
| 139 |
if (names.length() >= 20000) { |
| 140 |
qDebug() << QCoreApplication::translate("main", "Too many files! Aborting ..."); |
| 141 |
exit(-1); |
| 142 |
} |
| 143 |
names += findFiles(startDir + QDir::separator() + subdir); |
| 144 |
} |
| 145 |
return names; |
| 146 |
} |
| 147 |
|
| 148 |
// Utility function that prints the results of the map in decreasing order based on the value. |
| 149 |
void printHighestResult(const WordCount &countedWords, qsizetype nResults) |
| 150 |
{ |
| 151 |
using pair = QPair<QString, int>; |
| 152 |
QList<pair> vec; |
| 153 |
|
| 154 |
std::copy(countedWords.keyValueBegin(), countedWords.keyValueEnd(), |
| 155 |
std::back_inserter<QList<pair>>(vec)); |
| 156 |
std::sort(vec.begin(), vec.end(), |
| 157 |
[](const pair &l, const pair &r) { return l.second > r.second; }); |
| 158 |
|
| 159 |
qDebug() << QCoreApplication::translate("main", "Most occurring words are:"); |
| 160 |
for (qsizetype i = 0; i < qMin(vec.size(), nResults); ++i) |
| 161 |
qDebug() << vec[i].first << " : " << vec[i].second; |
| 162 |
} |