Code optimization
最近在寫 fuzzy 作業,這個作業需要寫程式,本來是想用 Matlab 寫的,但寫了一小段之後就放棄了,因為 Matlab 這個程式語言的彈性實在太差,為了寫一個 function 還要新建一個檔案,實在有夠鳥。最後我還是用我喜歡的程式語言 Python 寫,輕鬆愉快啊。我遇到一個程式碼最佳化的問題,原來的一段程式碼如下:
修改成
速度從 0.98 sec -> 0.12 sec,提升了 8.17 倍啊!其實程式碼在完全沒有最佳化所花費的時間是 2.5 sec,所以最佳化所提升的效率是 20.83 倍,真是恐怖。
English translation of the above:
Recently I have to write my fuzzy homework. Firstly, I planned to use the Matlab programming language to do this job. But, after writting a piece of source code, I gave up because the Matlab programming language is hard to use. When I want to write a function, I have to write this function in a new file! So finally I turned to my favorite language, Python, and the homework is done within an hour.
The second piece of source code is the optimized version of the first piece of source code. The first one takes 0.98 sec and the second one takes 0.12 sec. The performance improvement is 0.98/0.12 = 8.17. Actually the original unoptimized one takes 2.5 sec, so the optimization makes my program 2.5/0.12 = 20.83 times faster. Wow!!!
ps. It is painful to embed the source code in the article. In WYSIWYG mode, the source code looks awful.
for i in range(1,12):
for j in range(1,12):
mu_Ai = mu_A(i,x)
mu_Aj = mu_A(j,y)
t1 = t1 + mu_Ai * mu_Aj
t2 = t2 + g(step*(j-1)) * mu_Ai * mu_Aj
修改成
for i in range(1,12):
mu_Ai = mu_A(i,x)
if abs(mu_Ai) < eps:
continue
for j in range(1,12):
mu_Aj = mu_A(j,y)
if abs(mu_Aj) < eps:
continue
t1 = t1 + mu_Ai * mu_Aj
t2 = t2 + g(step*(j-1)) * mu_Ai * mu_Aj
速度從 0.98 sec -> 0.12 sec,提升了 8.17 倍啊!其實程式碼在完全沒有最佳化所花費的時間是 2.5 sec,所以最佳化所提升的效率是 20.83 倍,真是恐怖。
English translation of the above:
Recently I have to write my fuzzy homework. Firstly, I planned to use the Matlab programming language to do this job. But, after writting a piece of source code, I gave up because the Matlab programming language is hard to use. When I want to write a function, I have to write this function in a new file! So finally I turned to my favorite language, Python, and the homework is done within an hour.
The second piece of source code is the optimized version of the first piece of source code. The first one takes 0.98 sec and the second one takes 0.12 sec. The performance improvement is 0.98/0.12 = 8.17. Actually the original unoptimized one takes 2.5 sec, so the optimization makes my program 2.5/0.12 = 20.83 times faster. Wow!!!
ps. It is painful to embed the source code in the article. In WYSIWYG mode, the source code looks awful.