簡體   English   中英

C ++:簡單的多線程示例不比單線程快

[英]c++: simple multi-threading example not faster than single thread

我寫了一個非常簡單的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;

}

對我來說,程序的輸出是

time single-threading: 0.755919 sec 
time multi-threading:  0.746857 sec

我用編譯我的代碼

g++ cpp_tasksize.cpp -std=c++0x -pthread

我在24核Linux機器上運行

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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM