對比三種併發模型創建/銷毀開銷:
測試循環 1000 次創建並等待結束,統計總耗時 (微秒)。
#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 |
CC=g++
CFLAGS=-std=c++11 -pthread -O2
all: test
test: test.cpp
$(CC) $(CFLAGS) -o test test.cpp