我想比较使用不同过程的矩阵乘法(1, 2 ,4)
我使用 2 个进程的代码,fork 一次,让 child 成为 parent 并进行 1/2 计算
if (cpid == 0) { /* Code executed by child */
for (int i = 0; i < dimension / 2; i++)
{
for (int j = 0; j < dimension; j++)
{
//matrix multiplication
}
}
exit(EXIT_SUCCESS);
} else { /* Code executed by parent */
for (int i = dimension / 2; i < dimension; i++)
{
for (int j = 0; j < dimension; j++)
{
//matrix multiplication
}
}
}
以及4进程的代码,fork一次,然后child和parent再次fork,用4进程做1/4计算
cpid = fork();
if (cpid == 0)
{
cpid = fork();
if (cpid == 0)
{
for (int i = 0; i < dimension / 2; i++)
{
for (int j = 0; j < dimension / 2; j++)
{
//matrix multiplication
}
}
exit(EXIT_SUCCESS);
}
else{
for (int i = 0; i < dimension / 2; i++)
{
for (int j = dimension / 2; j < dimension; j++)
{
//matrix multiplication
}
}
exit(EXIT_SUCCESS);
}
}
else{
cpid = fork();
if (cpid == 0)
{
for (int i = dimension / 2; i < dimension; i++)
{
for (int j = 0; j < dimension / 2; j++)
{
//matrix multiplication
}
}
exit(EXIT_SUCCESS);
}
else{
for (int i = dimension / 2; i < dimension; i++)
{
for (int j = dimension / 2; j < dimension; j++)
{
//matrix multiplication
}
}
}
}
完整代码是:http ://codepad.org/MmjRiBIN
令我惊讶的是速度是 2 > 4 > 1 。
1
elapsed 5147.936000 ms
2
elapsed 2821.225000 ms
4
elapsed 3129.096000 ms
我想不通。