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程式設計
58
|
第二章
在最佳化期間進行單元測試以維持正確性
如果你還沒對你的程式碼進行單元測試,那麼,你很可能正在傷害你的長期生產力。Ian
有很尷尬的經驗,他曾經花了一整天的時間最佳化他的程式碼,但因為不方便的關係而
將單元測試停掉,最後卻發現,效能大幅提升的原因竟然是因為毀損了他正在改進的一
部分演算法。你不需要犯這樣的錯誤,一次都不要。
除了單元測試之外,你也應該考慮使用
coverage.py
,它檢查哪幾行程式碼被你的測試
所涵蓋,並且識別出未被涵蓋的部分。這迅速讓你釐清是否正在測試你要最佳化的程式
碼,因此,任何可能在最佳化過程中潛伏進來的錯誤都會迅速地被捕捉。
無操作 @profile 裝飾器
如果你的程式碼使用來自
line_profiler
memory_profiler
@profile
,你的單元測試
會發生
NameError
的例外,原因是,單元測試框架不會把
@profile
裝飾器注入本地名稱
空間。這裡所顯示的無操作裝飾器(no-op decorator)會解決這個問題,將它增加到你
正在測試的程式碼區塊,並且在完成時移除它,是最容易的做法。
透過使用無操作裝飾器,你不需要修改你的程式碼,就能夠執行你的單元測試。這表
示,你能夠在每次由效能分析引導的最佳化之後執行你的測試,所以你不會因為不良的
最佳化步驟而導致意外的錯誤。
假設我們有範例 2-20 所示的簡單
ex.py
模組,它包含單元測試(針對
nosetests
)以及
我們一直在使用
line_profiler
memory_profiler
進行效能分析的函式。 ...
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