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

高效能PYTHON程式設計

by Micha Gorelick, Ian Ozsvald
August 2015
Intermediate to advanced
384 pages
7h 42m
Chinese
GoTop Information, Inc.
Content preview from 高效能PYTHON程式設計
矩陣與向量計算
|
129
numexpr ︰讓就地操作更快速且更容易
numpy
的向量運算最佳化的一個缺點是它一次只發生在一個操作上,也就是說,在我們
使用
numpy
向量進行
A
*
B
+
C
的操作時,首先,整個
A
*
B
的操作完成,資料被儲存在暫
時性的向量中;接著,這個新向量被加上
C
。範例 6-14 的擴散程式碼的就地版本很清楚
地顯示這件事。
不過,有許多模組能夠幫忙處理這個問題。
numexpr
模組能夠將整個向量運算式(vector
expression)編譯成非常有效率的程式碼,這段程式碼經過最佳化,將快取未命中與使
用的暫時性空間減到最小。另外,這些運算式能夠利用多個 CPU 核心(更多資訊,請
參閱第 9 章),以及針對 Intel 晶片的特殊化指令,讓效能最大化。
把程式碼改為使用
numexpr
是非常容易的︰只要將運算式重寫成具有指向區域變數之參
考的字串。這些運算式在幕後被編譯(並且被快取,好讓對相同運算式的呼叫不會引發
相同的編譯成本),並且使用最佳化的程式碼來執行。範例 6-19 顯示,將
evolve
函式改
為使用
numexpr
是非常簡單的,在此案例中,我們選擇使用
evaluate
函式的
out
參數,
好讓
numexpr
不去配置要將計算結果回傳給它的新向量。
範例
6-19 
使用
numexpr
進一步最佳化大型矩陣運算
from numexpr import evaluate
def evolve(grid, dt, next_grid, D=1):
laplacian(grid, next_grid) ...
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.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

Kafka权威指南

Kafka权威指南

Neha Narkhede, Gwen Shapira, Todd Palino
手把手教会你linux

手把手教会你linux

桑德.范.乌格特
流畅的Python

流畅的Python

Luciano Ramalho
精通機器學習

精通機器學習

Aurélien Géron

Publisher Resources

ISBN: 9789863477105