【发布时间】:2012-12-29 01:09:59
【问题描述】:
当我调用函数时,执行时间是 6.8 秒。 从线程调用它的时间是 3.4 秒 使用 2 线程时 1.8 秒。无论我使用什么优化,口粮都保持不变。
在 Visual Studio 中,时间是预期的 3.1、3 和 1.7 秒。
#include<math.h>
#include<stdio.h>
#include<windows.h>
#include <time.h>
using namespace std;
#define N 400
float a[N][N];
struct b{
int begin;
int end;
};
DWORD WINAPI thread(LPVOID p)
{
b b_t = *(b*)p;
for(int i=0;i<N;i++)
for(int j=b_t.begin;j<b_t.end;j++)
{
a[i][j] = 0;
for(int k=0;k<i;k++)
a[i][j]+=k*sin(j)-j*cos(k);
}
return (0);
}
int main()
{
clock_t t;
HANDLE hn[2];
b b_t[3];
b_t[0].begin = 0;
b_t[0].end = N;
b_t[1].begin = 0;
b_t[1].end = N/2;
b_t[2].begin = N/2;
b_t[2].end = N;
t = clock();
thread(&b_t[0]);
printf("0 - %d\n",clock()-t);
t = clock();
hn[0] = CreateThread ( NULL, 0, thread, &b_t[0], 0, NULL);
WaitForSingleObject(hn[0], INFINITE );
printf("1 - %d\n",clock()-t);
t = clock();
hn[0] = CreateThread ( NULL, 0, thread, &b_t[1], 0, NULL);
hn[1] = CreateThread ( NULL, 0, thread, &b_t[2], 0, NULL);
WaitForMultipleObjects(2, hn, TRUE, INFINITE );
printf("2 - %d\n",clock()-t);
return 0;
}
次:
0 - 6868
1 - 3362
2 - 1827
CPU - Core 2 Duo T9300
操作系统 - Windows 8、64 位
编译器:mingw32-g++.exe,gcc 4.6.2版
编辑:
尝试了不同的顺序,相同的结果,甚至尝试了不同的应用程序。 任务管理器显示函数和 1 个线程的 CPU 利用率约为 50%,2 个线程的 CPU 利用率为 100%
每次调用后所有元素的总和都是一样的:3189909.237955
Cygwin 结果:2.5、2.5 和 2.5 秒 Linux 结果(pthread):3.7、3.7 和 2.1 秒
@borisbn 结果:0 - 1446 1 - 1439 2 - 721。
【问题讨论】:
-
我能感觉到神秘的打字......
-
@SethCarnegie Nah... 我无法一眼发现问题,而且我没有安装 mingw32。
-
是的,尝试不同的顺序,看看是否会有所不同。我敢打赌“第一次”需要更长的时间,而不是线程与无线程。
-
MinGW 4.6.2。正是你的代码。编译选项:-O2。结果:
0 - 1446 1 - 1439 2 - 721。std::thread的结果相同。我试图在函数调用之前运行线程,我将float a[N][N];移动到struct b中 - 结果没有改变 -
@user1978768 这是一个 exe 文件,由我的 mingw 从您的代码编译 - dl.dropbox.com/u/46469564/a.exe
标签: c++ multithreading performance function mingw