Eisen's Blog

© 2023. All rights reserved.

Some Thing about Python

March 29, 2011

A major rule of thumb in Python is to code for simplicity and readability first and worry about performance later, after your program is working, and after you’ve proved that there is a genuine performance concern. More often than not, your code will be quick enough as it is. If you do need to tweak code for performance, though, Python includes tools to help you out, including the time and timeit modules and the profile module.


We should forget about small efficiencies, say about 97% of the time: Premature optimization is the root of all evil.—Donald Knuth

而且,对效率的处理,应该在出现效率问题的时候才开始考虑吧。今天看Bruce Eckel的Thinking in Patterns with Java 最开始的章节里就讲到了这个所谓的"premature optimization",他引用了Knuth的话,强调除非你真的测试到这部分代码确实很耗时,需要对其优化,不然不要主观臆断的去提前优化它,这样的做法很浪费开发时间。纵使你的感觉是对的(那段代码确实很耗时!),他依然主张要从全局去考虑:整个程序的运行中,90%的时间浪费在10%的代码之中,那你所考虑的代码真的被包含进去了么?去花时间处理那10%就可以了,我们的时间是很宝贵的。其实道理很简单:完美是不可能的,去用最短的时间获取最大的优化吧。