OpenMp并行计算,为嘛双核没单核快,还比单核慢三倍

4lan 2011-07-01 03:25:44
这个是没使用OpenMp的代码:50万*5000*次乘法运算 cpu占用50%也就是一个核心,耗费大概十秒

#include "stdafx.h"
#include <Windows.h>


int _tmain(int argc, _TCHAR* argv[])
{
unsigned long ticks1,ticks2;
ticks1 = GetTickCount();

unsigned long a=1;

for (int i = 1; i < 500000; i++)
{
for (int i = 1; i < 5000; i++)
{
a=1;
a=a*i;
}
}

printf("%d\n",a);
ticks2 = GetTickCount();

ticks1=ticks2-ticks1;
printf("程序经过毫秒数:%d",ticks1);
getchar();
return 0;
}

这个是使用OpenMp的运算。

添加omp文件头

将 Project 的Properties中C/C++里Language的OpenMP Support开启

在要使用openmp的地方 添加 #pragma omp parallel

结果:cpu占用100%两个核心,但是耗时30秒。。。。。。。搞不懂呀

#include "stdafx.h"
#include <Windows.h>
#include <omp.h>


int _tmain(int argc, _TCHAR* argv[])
{
unsigned long ticks1,ticks2;
ticks1 = GetTickCount();

unsigned long a=1;
#pragma omp parallel for
for (int i = 1; i < 500000; i++)
{
for (int i = 1; i < 5000; i++)
{
a=1;
a=a*i;
}
}

printf("%d\n",a);
ticks2 = GetTickCount();

ticks1=ticks2-ticks1;
printf("程序经过毫秒数:%d",ticks1);
getchar();
return 0;
}
...全文
204 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
book_singman 2011-08-02
  • 打赏
  • 举报
回复
看看是不是threads 有冲突
abo33 2011-07-21
  • 打赏
  • 举报
回复
也许是线程之间冲突了~
副组长 2011-07-01
  • 打赏
  • 举报
回复
不会,#pragma omp 有问题吧?
大概你是每个核心都算了一遍。
#pragma omp parallel 后面写公有或似有变量
{
#pragma omp for
for(...)
{
...
}
}
4lan 2011-07-01
  • 打赏
  • 举报
回复
找半天,确信这个帖子消失了。。。

15,471

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 进程/线程/DLL
社区管理员
  • 进程/线程/DLL社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧