A more pythonic way of writting
eric
eric at ericaro.net
Fri Dec 5 20:50:07 EST 2008
On Dec 6, 12:19 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> On Fri, 05 Dec 2008 07:44:21 -0800, eric wrote:
> > I like to believe that the less the 'debug pointer' stands in the python
> > code, the fastest the code is (or is potentially)
>
> What's a debug pointer?
>
> Pre-mature optimization is the root of evil in programming. Unless you
> have actually *measured* the speed of the code, how do you know you
> aren't making it slower instead of faster?
>
> Experience with other languages often is misleading when programming with
> Python. If you are used to programming in C, for example, then you will
> tend to program one way because comparisons are fast and moving records
> is slow. But in Python, comparisons can be slow and moving records is
> fast, so the C programmer's intuitions about "fast code" are often
> pessimations instead of optimizations.
>
> --
> Steven
you are right about premature optimization. I cannot disagree.
My 'rule of thumb' was more about that:
1/ keep the code the more descriptive and the less procedural as
possible.
2/ the less instructions you write, the more optimization you'll get
from the others
the hypercube function is cool, and I would use it, if I weren't in
charge of maintaining the code.
I've done some 'timeit'
import timeit
t1 = timeit.Timer(
"""
h1 = hypercube(6)
""",
"""def hypercube(ndims):
return [[i&mask==mask for mask in [1<<j for j
in range(ndims)] ] for i in range(1<<ndims)]""")
t2 = timeit.Timer(
"""
h2 = [h for h in hypercube(6)]
""",
"""def hypercube(ndims):
if ndims == 0:
yield ()
return
for h in False,True:
for y in hypercube(ndims-1):
yield (h,)+y""")
M= 100000
array_method = t1.timeit(M)
recursion_method = t2.timeit(M)
print "array method %s"%array_method
print "recursion method %s"%recursion_method
print "recursion is %s%% slower"%( (recursion_method - array_method)/
recursion_method*100)
"""
console result
array method 41.2270488739
recursion method 48.3009829521
recursion is 14.6455281981% slower
"""
well, nothing drastic here.
More information about the Python-list
mailing list