c++ - 如何在 C++ 中使用多个线程对我的系统进行基准测试?
问题描述
我已经简化了我的代码,它可以编译,但它什么也没做。它也不会出错。在这个例子中,我试图让 7 个线程(在我的 8 核处理器上)写入一个变量来对我的系统进行基准测试。我想用多个线程来做这个,看看它是否更快。它基于在我添加多线程之前工作的其他代码。当我运行时,它就会终止。它应该每秒显示所有线程一起完成的总迭代次数的进度。其中一些包含来自我正在处理的其他代码。
我还想在按下 Ctrl-C 时优雅地终止所有 7 个线程。帮助将不胜感激。谢谢!
//Compiled using: g++ ./test.cpp -lpthread -o ./test
#include <stdio.h>
#include <string>
#include <iostream>
#include <time.h>
#include <ctime>
#include <ratio>
#include <chrono>
#include <iomanip>
#include <locale.h>
#include <cstdlib>
#include <pthread.h>
using namespace std;
using namespace std::chrono;
const int NUM_THREADS = 7;
const std::string VALUE_TO_WRITE = "TEST";
unsigned long long int total_iterations = 0;
void * RunBenchmark(void * threadid);
class comma_numpunct: public std::numpunct < char > {
protected: virtual char do_thousands_sep() const {
return ',';
}
virtual std::string do_grouping() const {
return "\03";
}
};
void * RunBenchmark(void * threadid) {
unsigned long long int iterations = 0;
std::string benchmark;
int seconds = 0;
std::locale comma_locale(std::locale(), new comma_numpunct());
std::cout.imbue(comma_locale);
auto start = std::chrono::system_clock::now();
auto end = std::chrono::system_clock::now();
do {
start = std::chrono::system_clock::now();
while ((std::chrono::duration_cast < std::chrono::seconds > (end - start).count() != 1)) {
benchmark = VALUE_TO_WRITE;
iterations += 1;
}
total_iterations += iterations;
iterations = 0;
cout << "Total Iterations: " << std::setprecision(0) << std::fixed << total_iterations << "\r";
} while (1);
}
int main(int argc, char ** argv) {
unsigned long long int iterations = 0;
int tc, tn;
pthread_t threads[NUM_THREADS];
for (tn = 0; tn < NUM_THREADS; tn++) {
tc = pthread_create( & threads[tn], NULL, & RunBenchmark, NULL);
}
return 0;
}
解决方案
推荐阅读
- c++ - 在 BST 中插入节点的逻辑错误
- r - 使用grid.raster在列表中的每个ggplot对象上叠加图像的方法?
- oracle-sqldeveloper - sqldeveloper + voltdb 连接
- android - 如何在子节点嵌套子键上创建索引?
- django - DRF:在字段中使用“源”进行序列化期间的奇怪行为
- python - Python 3 tkinter | 网址中的图片未显示
- php - 如何在 Wordpress PHP 中动态添加子菜单?
- php - 如何显示多个连续的html元素
- google-cloud-functions - 我可以使用谷歌云函数进行多少次并行的 rest API 调用?
- javascript - 如何修复 VS Code 中 ES Next "::" 绑定运算符的语法错误?