Stats

Popular Posts

Followers

Mathematica 教學 When to use Parallel Computing

戴忠淵 於 2011年6月29日星期三 下午12:46 發表


Q: 甚麼樣的狀況比較適合用平行運算

test[ntemp_Integer]:=Block[{n=ntemp, data, t1, t2},

(* 隨機產生n條具實數解的二元一次方程式 *)
data=Select[RandomReal[{0, 1}, {n, 3}], #[[2]]^2-4*#[[1]]*#[[3]] >= 0 &];
(* 不使用平行運算求根 *)
t1=AbsoluteTiming[Map[Quiet@Solve[#.{x^2, x, 1}==0, x]&, data]];
(* 使用平行運算求根 *)
t2=AbsoluteTiming[ParallelMap[Quiet@Solve[#.{x^2, x, 1}==0, x]&, data]];
(* 輸出計算時間 *)
{n, t1[[1]], t2[[1]]}]

(* 將n=100,200,...,10000個實驗一次 *)
sim=test[#]&/@Range[100, 10000, 100]

(* 繪出計算時間圖 *)
plot1=ListLinePlot[{sim[[All, {1, 2}]], sim[[All, {1, 3}]]}]
Labeled[plot1, Grid[{Graphics[{#[[1]], Thickness[0.1], Line[{{0, 0}, {1, 0}}]},
ImageSize->{24, 24}, AspectRatio->8/24,
ImagePadding->0], #[[2]]}&/@
Transpose@{plot1[[1,2, 1, {3, 4}, 1]],
{"不使用平行運算", "使用平行運算"}}],
{Right, Top}
]


要能進行平行運算的條件是每次的計算是獨立的。此外,由實驗也可以發現當計算次數少的時候,平行運算並沒有太大的好處,但計算次數大的時候就能有效的節省計算時間。
Tags:

讀者回應 ( 0 意見 )

發佈留言

Please leave your name and tell me what you thought about this site. Comments, suggestions and views are welcomed.

如果這篇文章對你有幫助,那請留個訊息給我~