c ++:简单的多线程示例并不比单线程快

Oli*_*ken 2 c++ multithreading

我在C++中为多线程编写了一个非常简单的例子.为什么多线程和单线程具有大致相同的执行时间?

码:

#include <iostream>
#include <thread>
#include <ctime>

using namespace std;

// function adds up all number up to given number
void task(int number)
{
    int s = 0;
    for(int i=0; i<number; i++){
        s = s + i;
    }
}

int main()
{

    int n = 100000000;

    ////////////////////////////
    // single processing      //
    ////////////////////////////

    clock_t begin = clock();

    task(n);
    task(n);
    task(n);
    task(n);

    clock_t end = clock();
    double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
    cout  << "time single-threading: "<< elapsed_secs << " sec" << endl;    

    ////////////////////////////
    // multiprocessing        //
    ////////////////////////////

    begin = clock();

    thread t1 = thread(task, n);
    thread t2 = thread(task, n);
    thread t3 = thread(task, n);
    thread t4 = thread(task, n);

    t1.join();
    t2.join();
    t3.join();
    t4.join();

    end = clock();
    elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
    cout << "time multi-threading:  " << elapsed_secs << " sec" << endl;

}
Run Code Online (Sandbox Code Playgroud)

对我来说,程序的输出是

time single-threading: 0.755919 sec 
time multi-threading:  0.746857 sec
Run Code Online (Sandbox Code Playgroud)

我编译我的代码

g++ cpp_tasksize.cpp -std=c++0x -pthread
Run Code Online (Sandbox Code Playgroud)

我在一台24核Linux机器上运行

ngl*_*lee 5

clock()测量处理器时间,您的进程花费在您的CPU上的时间.在一个多线程程序中,它会增加每个线程在你的cpu上花费的时间.据报道,您的单线程和多线程实现需要大约相同的时间才能运行,因为它们总体上进行了相同数量的计算.

您需要的是测量挂钟时间.chrono想要测量挂钟时间时使用库.

#include <chrono>

int main ()
{
    auto start = std::chrono::high_resolution_clock::now();

    // code section

    auto end = std::chrono::high_resolution_clock::now();
    std::cout << std::chrono::duration<double, std::milli>(end - start).count() << " ms\n";
}
Run Code Online (Sandbox Code Playgroud)