【发布时间】:2014-01-25 01:27:09
【问题描述】:
我做了一个小程序来观察使用两个线程的速度。我正在计时填充数组的过程。 A 主线程和 thread1 调用 function_1 来初始化数组的不同部分。我期待通过使用两个线程来看到更快的结果。相反,我的时间变慢了,注释掉的代码执行得更快。我哪里错了?
#include <chrono>
#include <iostream>
#include <vector>
#include <thread>
void function_1(int I, int J, int *B){
for (int i = I; i<(J+1); i++) {
B[i] = 100;
//std::cout << B[i] << std::endl;
}
}
int *count;
int main(int argc, const char * argv[])
{
count = new int[20000];
std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
//function_1(0, 19999, count);
std::thread thread1(function_1, 0, 9999, count);
thread1.join();
function_1(10000, 19999, count);
std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
auto time_span = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count();
std::cout << "time taken is :" <<time_span << " ms"<<std::endl;
return 0;
}
【问题讨论】:
标签: c++ arrays multithreading performance