Skip to Main Content
高效能PYTHON程式設計
book

高效能PYTHON程式設計

by Micha Gorelick, Ian Ozsvald
August 2015
Intermediate to advanced content levelIntermediate to advanced
384 pages
7h 42m
Chinese
GoTop Information, Inc.
Content preview from 高效能PYTHON程式設計
228
|
第九章
尋找質數
接下來,我們會針對大範圍的數字測試質數,這是與估計 pi 不同的問題,因為工作負荷
隨著你在數字範圍裡的位置而異,而且每一個數字的檢查都有不可預期的複雜度。我們
可以建立一個檢查質數性(primality)的循序程序,然後將一組組可能的數字傳送給每
個行程做檢查。這個問題是高度平行的(embarrassingly parallel),這表示,沒有狀態需
要被共用。
multiprocessing
模組讓控制工作負荷變容易,所以我們會研究一下如何調整工作佇列,
運用(及誤用)我們的計算資源,並且探索如何稍微更有效率地使用我們的資源,這表
示,我們會檢視
負載平衡
load balancing
),試著將複雜度不固定的任務有效率地分散
到固定一組資源上。
我們會將本書稍早所顯示的演算法(參見第 10 頁的〈理想化計算 vs. Python 虛擬機器〉
稍微做一點改善,在遇到偶數時提早退出;參見範例 9-4
範例
9-4 
使用
Python
尋找質數
def check_prime(n):
if n % 2 == 0:
return False
from_i = 3
to_i = math.sqrt(n) + 1
for i in xrange(from_i, int(to_i), 2):
if n % i == 0:
return False
return True
在使用這個方法測試質數時,工作負荷會有多大變化?圖 9-10 顯示
n
10,000
1,000,000
的質數性檢查的時間成本如何遞增。 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

流畅的Python

流畅的Python

Luciano Ramalho
手把手教会你linux

手把手教会你linux

桑德.范.乌格特

Publisher Resources

ISBN: 9789863477105