首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++11 std::thread vs POSIX pthread 性能對比測試

     編輯:關於C++

測試環境與結構

對比三種併發模型創建/銷毀開銷:

  1. 進程 `fork()` + `wait()`
  2. POSIX 線程 `pthread_create()` + `pthread_join()`
  3. C++11 `std::thread` + `join()`

測試循環 1000 次創建並等待結束,統計總耗時 (微秒)。

核心代碼 (C++)

#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

void* posix_fun(void*) { return nullptr; }
void cpp_fun() {}

int main() {
    struct timeval tv1, tv2;
    unsigned long long elapse;
    int i;
    pthread_t tid;
    pid_t pid;

    // 1. POSIX Threads
    gettimeofday(&tv1, nullptr);
    for (i = 0; i < 1000; i++) {
        pthread_create(&tid, nullptr, posix_fun, nullptr);
        pthread_join(tid, nullptr);
    }
    gettimeofday(&tv2, nullptr);
    elapse = (tv2.tv_sec - tv1.tv_sec) * 1000000ULL + (tv2.tv_usec - tv1.tv_usec);
    cout << "pthread: " << elapse << " us (" << elapse/1000000.0 << " s)" << endl;

    // 2. C++11 std::thread
    gettimeofday(&tv1, nullptr);
    for (i = 0; i < 1000; i++) {
        thread t(cpp_fun);
        t.join();
    }
    gettimeofday(&tv2, nullptr);
    elapse = (tv2.tv_sec - tv1.tv_sec) * 1000000ULL + (tv2.tv_usec - tv1.tv_usec);
    cout << "std::thread: " << elapse << " us (" << elapse/1000000.0 << " s)" << endl;

    return 0;
}

編譯命令

g++ -std=c++11 -pthread -O2 test.cpp -o test

典型測試結果 (參考)

模型耗時 (1000次)相對性能
fork + wait~2.7 秒基準 (最慢)
pthread_create/join~1.6 秒快 ~1.7x
std::thread~1.8 秒快 ~1.5x,略慢於 pthread

結果分析

  • 進程最慢: 需複製頁表、文件描述符表等內核資源,上下文切換開銷大。
  • pthread 最快: 輕量級線程,僅分配棧空間、TCB,內核調度實體開銷小。
  • std::thread 略慢: 封裝層帶來微小開銷 (异常處理、RAII 管理、可調用對象包裝),功能更豐富 (move 語義、硬件並發查詢等)。
  • 優化建議: 高頻創建銷毀場景應使用線程池,避免重複系統調用開銷。

Makefile 示例

CC=g++
CFLAGS=-std=c++11 -pthread -O2
all: test
test: test.cpp
	$(CC) $(CFLAGS) -o test test.cpp
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved