c++使用多线程提速
#include<iostream>
#include <thread>
#include <chrono>
#include <unistd.h> //可以使用sleep函数
using namespace std;
int NUM = 60000;
int TNUM = 2;
int func1(int* ptr){
for(int i=0; i<NUM; i++){
*(ptr++) = i;
// ptr++;
// cout << *(ptr-1) << endl;
// ptr++;
}
return 0;
}
int func_split_num(int* ptr, int start, int end, int core){
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(core, &mask); // 指定第几个核运行,本程序
for(int i=start; i<end; i++){
*(ptr++) = i;
// sleep(1);
// cout << *(ptr-1) << endl;
}
return 0;
}
int func2(int* ptr){
thread thread1(func_split_num, ptr, 0, NUM/2, 11); // 线程开始
thread thread2(func_split_num, ptr+NUM/2, NUM/2, NUM, 13);
thread1.join(); // 等待线程结束,注意两个join写在最后面
thread2.join();
return 0;
}
int main()
{
int* arr = new int [NUM];
using milli = std::chrono::milliseconds;
// func1(arr);
// func2(arr);
int c =65535;
auto start = std::chrono::high_resolution_clock::now();
for(int i=0; i<c; i++){
func1(arr);
}
auto end = std::chrono::high_resolution_clock::now();
std::cout << "func1: "
<< (float)std::chrono::duration_cast<milli>(end - start).count()
<< " milliseconds\n";
start = std::chrono::high_resolution_clock::now();
for(int i=0; i<c; i++){
func2(arr);
}
end = std::chrono::high_resolution_clock::now();
std::cout << "func2: "
<< (float)std::chrono::duration_cast<milli>(end - start).count()
<< " milliseconds\n";
// 赋值并
for(int i=0; i<NUM; i++){
cout << arr[i] << "-check"<< endl;
}
return 0;
}
指定进程执行使用cpu内核
taskset -c 11 ./a.out
输出
func1: 10884 milliseconds
func2: 12298 milliseconds
未指定cpu内核
func1: 8933 milliseconds
func2: 6952 milliseconds
结论:ubuntu系统内,进程的内开启两个线程处理数据相比一个线程处理数据,指定进程使用cpu内核,多线程会降低性能,但是未指定运行cpu内核,线程是加速的,由此推理C语言多线程默认使用了多核