首页 > 解决方案 > 如何在 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++multithreadingbenchmarking

解决方案


推荐阅读