Skip to Content
Python高级编程(第2版)
book

Python高级编程(第2版)

by Posts & Telecom Press, Michał Jaworski, Tarek Ziadé
February 2024
Intermediate to advanced
423 pages
6h 9m
Chinese
Packt Publishing
Content preview from Python高级编程(第2版)

第11章 优化——一般原则与分析技术

“我们应该忘记小的效能,大约97%的情况:过早优化是万恶之源。”

——Donald Knuth

本章是关于优化的,并且提供一套一般原则和分析技术。它给出了每个开发人员应该注意的3个优化规则,并提供优化指南。最后,本章会关注如何找到瓶颈。

不管结果如何,优化需要付出一些代价。当一段代码正常工作时,如果不去管它,而不是试图花费很多成本使其更快,它可能(有时)运行的更好。进行任何类型的优化时,请注意以下几个规则。

  • 首先要能工作。
  • 从用户的角度考虑。
  • 保持代码的可读性。

一个很常见的错误是,在编写代码时就尝试优化代码。这是没有意义的,因为真正的瓶颈往往位于你从未想到过的地方。

应用程序通常由非常复杂的交互组成,并且,在真正使用它之前,我们不可能全面的了解应用程序的功能。

当然,这不是不去尝试优化一个函数或方法的原因。你应该非常细心并且尽可能降低其复杂性,避免无用的重复。但是第一个目标是使它正常工作。优化工作不应该阻碍这个首要目标。

对于行级代码,Python的哲学是用一种方法,最好是只有一种方法来做一件事。所以,只要你坚持使用Python化的语法,这些语法在第2章和第3章中提到过,你的代码应该是很好的。通常,编写较少的代码比编写更多的代码更好更快。

在到你的代码正常工作以及你准备好调优之前,不要做任何以下这些事情。

  • 开始编写全局字典以缓存函数的数据。
  • 考虑使用C语言或者混合语言(如Cython)外部化一部分代码。
  • 查找一些进行基本计算的外部库。

对于非常专业的领域,如科学计算或游戏,专业库的使用以及外部化可能从一开始就是不可避免的。另一方面,使用像NumPy这样的库可以缓解特定功能的开发,并且最终产生更简单和更快的代码。此外,如果有一个很好的库可以满足你的需求,你就没必要重新写一个。 ...

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

Hadoop实际解决方案手册

Hadoop实际解决方案手册

Posts & Telecom Press, JONATHAN OWENS, Lentz Jon, Femiano Brian
TensorFlow机器学习

TensorFlow机器学习

Posts & Telecom Press, Quan Hua, Shams Ul Azeem, Saif Ahmed
Python和NLTK实现自然语言处理

Python和NLTK实现自然语言处理

Posts & Telecom Press, Nitin Hardeniya
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835887745