pthread_join是一个瓶颈
pthread_join is being a bottleneck
我有一个应用程序,其中pthread_join
是瓶颈。我需要帮助来解决这个问题。
void *calc_corr(void *t) {
begin = clock();
// do work
end = clock();
duration = (double) (1000*((double)end - (double)begin)/CLOCKS_PER_SEC);
cout << "Time is "<<duration<<"t"<<h<<endl;
pthread_exit(NULL);
}
int main() {
start_t = clock();
for (ii=0; ii<16; ii++)
pthread_create(&threads.p[ii], NULL, &calc_corr, (void *)ii);
for (i=0; i<16; i++)
pthread_join(threads.p[15-i], NULL);
stop_t = clock();
duration2 = (double) (1000*((double)stop_t - (double)start_t)/CLOCKS_PER_SEC);
cout << "n Time is "<<duration2<<"t"<<endl;
return 0;
}
线程函数中打印的时间在40ms-60ms的范围内,其中主函数打印的时间为650ms-670ms。具有讽刺意味的是,我的串行代码运行时间为650ms-670ms。我能做些什么来减少pthread_join
所花费的时间?
提前感谢!
在Linux上,clock()
测量组合CPU时间它不测量墙时间
这就是为什么你会得到~640 ms = 16 * 40ms
。(如评论中所指出的)
要测量墙时间,您应该使用以下内容:
gettimeofday()
clock_gettime()
通过创建一些线程,您为系统增加了开销:创建时间、调度时间。创建线程需要分配堆栈等;调度意味着更多的上下文切换。此外,pthread_join suspends execution of the calling thread until the target thread terminates
。这意味着你希望线程1完成,当他完成时,你会尽快重新安排,但不是立即,然后你等待线程2,等等。
现在,你的计算机只有几个内核,比如一个或两个,而你正在创建16个线程。程序中最多有两个线程同时运行,只需添加它们的时钟测量值,就可以实现400 ms
。
同样,这取决于很多事情,所以我很快就了解了正在发生的事情。
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '