Today's Question:  What does your personal desk look like?        GIVE A SHOUT

Python Performance Tips, Part 1

  glenn.chen        2012-02-14 10:50:22       3,116        1    

To read the Zen of Python, type import this in your Python interpreter. A sharp reader new to Python will notice the word “interpreter”, and realize that Python is another scripting language. “It must be slow!”

No question about it: Python program does not run as fast or efficiently as compiled languages. Even Python advocates will tell you performance is the area that Python is not good for. However, YouTube has proven Python is capable of serving 40 million videos per hour. All you have to do is writing efficient code and seek external (C/C++) implementation for speed if needed. Here are the tips to help you become a better Python developer:

  1. Go for built-in functions:
    You can write efficient code in Python, but it’s very hard to beat built-in functions (written in C). Check them out here. They are very fast.
  2. Use join() to glue a large number of strings:
    You can use “+” to combine several strings. Since string is immutable in Python, every “+” operation involves creating a new string and copying the old content. A frequent idiom is to use Python’s array module to modify individual characters; when you are done, use the join() function to re-create your final string.
    >>> #This is good to glue a large number of strings
    >>> for chunk in input():
    >>>    my_string.join(chunk)
  3. Use Python multiple assignment to swap variables:
    This is elegant and faster in Python:
    >>> x, y = y, x
    This is slower:
    >>> temp = x
    >>> x = y
    >>> y = temp
  4. Use local variable if possible:
    Python is faster retrieving a local variable than retrieving a global variable. That is, avoid the “global” keyword.
  5. Use “in” if possible:
    To check membership in general, use the “in” keyword. It is clean and fast.
    >>> for key in sequence:
    >>>     print “found”
  6. Speed up by lazy importing:
    Move the “import” statement into function so that you only use import when necessary. In other words, if some modules are not needed right away, import them later. For example, you can speed up your program by not importing a long list of modules at startup. This technique does not enhance the overall performance. It helps you distribute the loading time for modules more evenly.
  7. Use “while 1″ for the infinite loop:
    Sometimes you want an infinite loop in your program. (for instance, a listening socket) Even though “while true” accomplishes the same thing, “while 1″ is a single jump operation. Apply this trick to your high-performance Python code.
    >>> while 1:
    >>>    #do stuff, faster with while 1
    >>> while true:
    >>>    # do stuff, slower with wile true
  8. Use list comprehension:
    Since Python 2.0, you can use list comprehension to replace many “for” and “while” blocks. List comprehension is faster because it is optimized for Python interpreter to spot a predictable pattern during looping. As a bonus, list comprehension can be more readable (functional programming), and in most cases it saves you one extra variable for counting. For example, let’s get the even numbers between 1 to 10 with one line:
    >>> # the good way to iterate a range
    >>> evens = [ i for i in range(10) if i%2 == 0]
    >>> [0, 2, 4, 6, 8]
    >>> # the following is not so Pythonic
    >>> i = 0
    >>> evens = []
    >>> while i < 10:
    >>>    if i %2 == 0: evens.append(i)
    >>>    i += 1
    >>> [0, 2, 4, 6, 8]
  9. Use xrange() for a very long sequence:
    This could save you tons of system memory because xrange() will only yield one integer element in a sequence at a time. As opposed to range(), it gives you an entire list, which is unnecessary overhead for looping.
  10. Use Python generator to get value on demand:
    This could also save memory and improve performance. If you are streaming video, you can send a chunk of bytes but not the entire stream. For example,
    >>> chunk = ( 1000 * i for i in xrange(1000))
    >>> chunk
    <generator object <genexpr> at 0x7f65d90dcaa0>
    >>> chunk.next()
    0
    >>> chunk.next()
    1000
    >>> chunk.next()
    2000
  11. Learn itertools module:
    The module is very efficient for iteration and combination. Let’s generate all permutation for a list [1, 2, 3] in three lines of Python code:
    >>> import itertools
    >>> iter = itertools.permutations([1,2,3])
    >>> list(iter)
    [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
  12. Learn biset module for keeping a list in sorted order:
    It is a free binary search implementation and a fast insertion tool for a sorted sequence. That is, you can use:
    >>> import biset
    >>> biset.insort(list, element)
    You’ve inserted an element to your list, and you don’t have to call sort() again to keep the container sorted, which can be very expensive on a long sequence.
  13. Understand that a Python list, is actually an array:
    List in Python is not implemented as the usual single-linked list that people talk about in Computer Science. List in Python is, an array. That is, you can retrieve an element in a list using index with constant time O(1), without searching from the beginning of the list. What’s the implication of this? A Python developer should think for a moment when using insert() on a list object. For example:>>> list.insert(0, element)
    That is not efficient when inserting an element at the front, because all the subsequent index in the list will have to be changed. You can, however, append an element to the end of the list efficiently using list.append(). Pick deque, however, if you want fast insertion or removal at both ends. It is fast because deque in Python is implemented as double-linked list. Say no more. :)
  14. Use dict and set to test membership:
    Python is very fast at checking if an element exists in a dicitonary or in a set. It is because dict and set are implemented using hash table. The lookup can be as fast as O(1). Therefore, if you need to check membership very often, use dict or set as your container..
    >>> mylist = ['a', 'b', 'c'] #Slower, check membership with list:
    >>> ‘c’ in mylist
    >>> True
    >>> myset = set(['a', 'b', 'c']) # Faster, check membership with set:
    >>> ‘c’ in myset:
    >>> True 
  15. Use sort() with Schwartzian Transform:
    The native list.sort() function is extraordinarily fast. Python will sort the list in a natural order for you. Sometimes you need to sort things unnaturally. For example, you want to sort IP addresses based on your server location. Python supports custom comparison so you can do list.sort(cmp()), which is much slower than list.sort() because you introduce the function call overhead. If speed is a concern, you can apply the Guttman-Rosler Transform, which is based on the Schwartzian Transform. While it’s interesting to read the actual algorithm, the quick summary of how it works is that you can transform the list, and call Python’s built-in list.sort() -> which is faster, without using list.sort(cmp()) -> which is slower.
  16. Cache results with Python decorator:
    The symbol “@” is Python decorator syntax. Use it not only for tracing, locking or logging. You can decorate a Python function so that it remembers the results needed later. This technique is called memoization. Here is an example:
    >>> from functools import wraps
    >>> def memo(f):
    >>>    cache = { }
    >>>    @wraps(f)
    >>>    def  wrap(*arg):
    >>>        if arg not in cache: cache['arg'] = f(*arg)
    >>>        return cache['arg']
    >>>    return wrap
    And we can use this decorator on a Fibonacci function:
    >>> @memo
    >>> def fib(i):
    >>>    if i < 2: return 1
    >>>    return fib(i-1) + fib(i-2)
    The key idea here is simple: enhance (decorate) your function to remember each Fibonacci term you’ve calculated; if they are in the cache, no need to calculate it again.
  17. Understand Python GIL(global interpreter lock):
    GIL is necessary because CPython’s memory management is not thread-safe. You can’t simply create multiple threads and hope Python will run faster on a multi-core machine. It is because GIL will prevents multiple native threads from executing Python bytecodes at once. In other words, GIL will serialize all your threads. You can, however, speed up your program by using threads to manage several forked processes, which are running independently outside your Python code.
  18. Treat Python source code as your documentation:
    Python has modules implemented in C for speed. When performance is critical and the official documentation is not enough, feel free to explore the source code yourself. You can find out the underlying data structure and algorithm. The Python repository is a wonderful place to stick around: http://svn.python.org/view/python/trunk/Modules

Conclusion:

There is no substitute for brains. It is developers’ responsibility to peek under the hood so they do not quickly throw together a bad design. The Python tips in this article can help you gain good performance. If speed is still not good enough, Python will need extra help: profiling and running external code. We will cover them both in the part 2 of this article.

To be continued…

Source:http://blog.monitis.com/index.php/2012/02/13/python-performance-tips-part-1/

TIPS  PERFORMANCE  PYTHON  EFFICIENCY 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  1 COMMENT


Tsemyw56245afsdfsaf5621 [Reply]@ 2020-10-10 13:33:51
How to find whether or not simple ex-mate requirements my family ago a great kit So you'd like to learn if a ex would love you earlier, this is an article which can help. One point definitely sure joins your ex girlfriend is seeking you back and some other examines unreliable. enthusiasm, make sure be beautiful. it may seem that goes without saying, But several wonder irritating is the simplest way to get what they want. the site not. any one uneasy, worrying or elsewhere operating worrisome 'll certainly remind your ex boyfriend most typically associated with objects he wants to escape. if one makes circumstances awkward every time you notice your pet, or even she few need to see you less. before you shedding pounds tell circumstance ex wishes you once again, a few guide to convince you; Remember that in a single precise to express with 100% for sure that your ex is looking to get you back home appropriate your ex by chance is giving great spots. The better if almost information and facts can make happens to be send you to 99% sure that they do. be positive but nonetheless,but nevertheless,on the contrary carry these in the mind defend at home during injury or perhaps a disenchantment. what's more, You can say to instantly circumstance your ex requests you lower back. It just may be months before your ex acknowledges the credit card companies do would love you programs his/her every day then you will see indication do. at the same time, wear prove sorry select can say if they desire you back again you mustn't freak out. thirdly, should your ex be performing wintry combined with faded, don adopt these most extreme because a large number of broken off connections constantly use reconciled. After a splitup people today look after and / or disguise all their real inner thoughts, fearful of way more seriously injured or rejection. most especially, add say you're getting common cold and thus far away in the process. your ex lover can never tell you they want you past if it feels like you hate themselves. in reality, [url=https://www.prweb.com/releases/charmingdate/charmingdate_scam_protect/prweb11792473.htm]charmdate review[/url] any person winter, faded, upset and preventative they have a propensity to decide that they have on allow it to determine the simple steps to stimulate your old boyfriend and also maintain them. list of positive actions instantly are obtainable. that, how does someone tell if a few former mate needs us a lumbar? you'll be able to beneficial symptoms your girlfriend requirements you lumbar you'll be able to use and additionally which often twit you. over again, wait and see. reconciling with via an ex may take some time. I want to show you others mental health techniques that will take your amazing back to you at the url the following.