哪一部分是平行的.因为应该是固定的,是不安全的
本文关键字:不安全 因为 一部分 | 更新日期: 2023-09-27 18:12:29
我有一个嵌套的For循环如下:
// This loop cannot be parallel because results of the next
// two loops will be used for next t
for (int t= 0; t< 6000000; t++)
// Calculations in the following two loops includes 75% of all time spend for.
for (int i= 0; i< 1000; i++)
{
for (int j= 0; j< 1000; j++)
{
if (Vxcal){V.x= ............. // some calculations }
if (Vycal){V.y= ............. // some calculations }
// Vbar is a two dimensional array
Vbar = V;
}
}
我把上面的代码改成:
// This loop cannot be parallel because results of the next
// two loops will be used for next t
for (int t= 0; t< 6000000; t++)
// Calculations in the following two loops includes 75% of all time spend for.
Parallel.for (0, 1000, i=>
{
Parallel.for (0, 1000, j=>
{
if (Vxcal){V.x= ............. // some calculations }
if (Vycal){V.y= ............. // some calculations }
// Vbar is a two dimensional array
Vbar = V;
}
}
当我运行代码结果不正确,需要几个小时而不是10分钟。我的问题是:这种For循环适合并行吗?这些循环只是一些数学计算。我怎样才能使这个平行For循环安全呢?
我发现了一个关键字"锁",这可以帮助我有一个安全的循环,但这个循环的哪一部分是不安全的?
我看到你修改了你的问题,加入了一些其他的数字。所以你的内循环现在执行了6000000*1000*1000,或者6,000,000,000,000次。以每秒40亿次计算的速度计算(这是你的计算机做不到的),这将需要1500秒,也就是25分钟。如果您获得了Parallel.For
的完美并行性,则可以在4核机器上将此时间减少到8.25分钟。如果你的计算又长又复杂,那么花几个小时来完成也就不足为奇了。
你的代码很慢,因为它做了很多工作。你需要一个更好的算法!
原始回答
考虑嵌套循环:
for (int t= 0; t< 5000000000; t++)
// Calculations in the following two loops includes 75% of all time spend for.
for (int i= 0; i< 5000000000; i++)
{
for (int j= 0; j< 5000000000; j++)
内循环(你的计算)正在执行5,000,000,000*5,000,000,000*5,000,000,000次。125,000,000,000,000,000,000,000,000,000,000是一个巨大的数字。即使你的计算机每秒能循环40亿次(它不能——甚至不能接近),它也需要31,250,000,000,000,000,000秒,或者大约9900亿年才能完成。在四核机器上使用多线程可以将时间缩短到2500亿年。
我不知道你想做什么,但你需要一个更好的算法,一台比你现有的计算机快5000亿倍的计算机,或者几千亿个处理器,如果你想在你的有生之年完成它。