c++ - Multithreaded algorithms work much slower
问题描述
I have tried with OpenMP and Cilk Plus. The result is the same, multithreading works slower.
I don't know what I'm doing wrong. I did what the guy did in this tutorial
His code works better in parallel, while the situation in mine is like this:
PARALLEL: Fibonacci number #42 is 267914296
Calculated in 33.026 seconds using 8 workers
SERIAL: Fibonacci number #42 is 267914296
Calculated in 2.110 seconds using 8 workers
I exactly copied the source code of the tutorial.
I also tried it with OpenMP, the same thing happens there too. I check the usage of CPU cores during the execution. They all work, it is fine.
I tried to change the number of workers with this command:
export CILK_NWORKERS=4
It appears as the number of workers increases, the algorithm runs slower. But sometimes it doesn't. I implemented Cilk codes on both C and C++. No difference.
This is the sequential Fibonacci function:
int fib_s(int n)
{
if (n < 2)
return n;
int x = fib_s(n-1);
int y = fib_s(n-2);
return x + y;
}
This is the parallel Fibonacci function:
int fib(int n)
{
if (n < 2)
return n;
int x = cilk_spawn fib(n-1);
int y = fib(n-2);
cilk_sync;
return x + y;
}
And I calculate running time like this in main()
function:
clock_t start = clock();
int result = fib(n);
clock_t end = clock();
double duration = (double)(end - start) / CLOCKS_PER_SEC;
Can anyone help me?
解决方案
推荐阅读
- r - MASS::glm.nb 包对某些数据集返回错误
- javascript - Flutter WEB的Firebase Analytics调试视图?
- python - 如何根据列值 pandas 添加到计数
- mysql - 我将如何组合这 2 个 SQL 语句?
- javascript - Discord.js:无法读取未定义的属性“缓存”
- java - 从 Thymeleaf 访问 Spring 中的属性文件
- c# - 将int转换为int?可能的更新?
- vb.net - 将列表中的所有值加一
- javascript - 在类扩展组件中, const state = [] 可以工作。我如何在函数 app() 组件中做类似的事情?
- python - 无需用户按回车即可获取用户的当前输入