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.
8 Comments:
為什麼用英文再寫一次啊...show off o_O
btw, 我看完第一段就笑了XD
By Anonymous, at 3:54 AM
部落格要全球化當然要用英文寫啊,用中文寫市場太小了。你可以用其它選擇一個身分,用匿名怪怪的...
By cpw, at 4:02 AM
原來是醬子啊...
那用anonymous好了XD
By Anonymous, at 4:05 AM
回得還真快,mbaq goo... 話說回來一開始先炫耀的人是你,詳見"我心似海洋"的回文。
By cpw, at 4:12 AM
竟然罵我...沒風度...
第一個字有簡碼...mbk jia...
By Anonymous, at 4:17 AM
謝謝喔... comment 不是讓你用來聊天的 XD
By cpw, at 4:23 AM
糟...被發現了XD ((((((((^_^)o
By Anonymous, at 4:29 AM
我不聊了,bye bye...
By cpw, at 4:31 AM
Post a Comment
<< Home