Welcome!

Machine Learning Authors: Elizabeth White, Zakia Bouachraoui, Carmen Gonzalez, Yeshim Deniz, Liz McMillan

Blog Feed Post

Python Performance Tips, Part 2

It’s a useful reminder that statically compiled code still matter. Just to name a few, Chrome, Firefox, MySQL, MS Office, and Photoshop are highly optimized software that many of us are using every day. Python, as an interpreted language, is not oblivious to this fact. Python alone cannot meet requirements in some domains where efficiency is a main priority. This is why Python supports infrastructure that touches the bare metal for you, by delegating heavy work to fast languages such as C. This is a critical feature for high-performance computing and embedded programming. Python Performance Tips Part 1 discussed how to use Python effectively. In part 2, we will cover profiling and extending Python.

  1. First, resist your temptation of optimization.

    Optimization will introduce complexity to your code base. Check the following list before integrating with other languages. If your solution is “good enough”, optimizing is not necessarily good.
    • Do your customers report speed problems?
    • Can you minimize hard disk I/O access?
    • Can you minimize network I/O access?
    • Can you upgrade your hardware?
    • Are you writing libraries for other developers?
    • Is your third-party software up-to-date?
  2. Profile code with tools, not with intuition.
    Speed problem can be subtle, so do not rely on intuition. Thanks to the “cprofiles” module, you can profile Python code by simply running
    “python -m cProfile myprogram.py”


    We wrote a test program (right). The profiling result is in the black box (above). The bottleneck here is the “very_slow()” function call. We can also see that “fast()” and “slow()” has been called 200 times each. This implies that if we can improve “fast()” and “slow()”, we will get a decent increase in performance. The cprofiles module can also be imported during runtime. This is useful for checking long-running processes.
  3. Review running-time complexity.
    After profiling, give some basic analysis of how fast your solution is. Constant time is ideal. Logarithm algorithm is stable. Factorial solution will not scale.
    O(1) -> O(lg n) -> O(n lg n) -> O(n^2) -> O(n^3) -> O(n^k) -> O(k^n) -> O(n!)
  4. Use third-party packages.
    There are many high-performance libraries and tools designed for Python. Here is a short list of useful acceleration packages.

  5. Use multiprocessing module for true concurrency.
    Because GIL (Global Interpreter Lock) will serialize threads, multi-threading in Python cannot speed up your code in multiprocessor machines nor in machine cluster. Therefore Python offers a multiprocessing module which can spawn extra processes instead of threads, lifting the limitation imposed by GIL. Furthermore, you can combine this tip with external C code, to make your program even faster.

    Note that a process is usually more expensive than a thread, since threads automatically share the same memory address space and file descriptors. This means that it will take more time to create a process, and likely cost more memory than creating a thread. This is something to consider if you plan to spawn many processes. 

  6. Let’s go native.

    So you’ve decided to use native code for performance. With the standard ctypes module, you can directly load compiled binary (.dll or .so files) into Python, without worrying about writing C/C++ code or build dependencies. For example, we wrote a program (on the right) that loads libc to generate random numbers.
    However, the overhead of ctypes binding is not light. You should consider ctypes as a quick glue to your OS libraries or device drivers for accessing hardware. There are several libraries such as SWIG, Cython, and Boost Python that introduce much less calling overhead than ctypes does. Here we pick Boost Python library to inter-operate with Python, because Boost Python supports object-oriented features such as class and inheritance. As we can see from the example (on the right), we keep the usual C++ code (line 1~7), and then import it later (line 21~24). The major work here is to write a wrapper (line 10~18).

 

Conclusion:

I hope the Python performance series has made you a better developer. At last, I would like to point out that while pushing performance to the limit is a fun game, premature optimization could turn it into a travesty. Python empowers you to interface with C-compatible languages seamlessly, but Python prefers development speed over executing speed with good reason. You have to ask yourself if users would pay extra for your hard-working hours on optimization. In addition, eliminating code readability just to save a few milliseconds almost never goes well. Developers in your team will always thank you for writing clean code. Stay close by the Python side, for life is short. :)

See also Python Performance Tips, Part 1

Share Now:del.icio.usDiggFacebook LinkedInBlinkListDZoneGoogle BookmarksRedditStumbleUponTwitterRSS

Read the original blog entry...

More Stories By Hovhannes Avoyan

Hovhannes Avoyan is the CEO of PicsArt, Inc.,

CloudEXPO Stories
There's no doubt that blockchain technology is a powerful tool for the enterprise, but bringing it mainstream has not been without challenges. As VP of Technology at 8base, Andrei is working to make developing a blockchain application accessible to anyone. With better tools, entrepreneurs and developers can work together to quickly and effectively launch applications that integrate smart contracts and blockchain technology. This will ultimately accelerate blockchain adoption on a global scale.
Cloud-enabled transformation has evolved from cost saving measure to business innovation strategy -- one that combines the cloud with cognitive capabilities to drive market disruption. Learn how you can achieve the insight and agility you need to gain a competitive advantage. Industry-acclaimed CTO and cloud expert, Shankar Kalyana presents. Only the most exceptional IBMers are appointed with the rare distinction of IBM Fellow, the highest technical honor in the company. Shankar has also received the prestigious Outstanding Technical Achievement Award three times - an accomplishment befitting only the most innovative thinkers. Shankar Kalyana is among the most respected strategists in the global technology industry. As CTO, with over 32 years of IT experience, Mr. Kalyana has architected, designed, developed, and implemented custom and packaged software solutions across a vast spectrum o...
When building large, cloud-based applications that operate at a high scale, it’s important to maintain a high availability and resilience to failures. In order to do that, you must be tolerant of failures, even in light of failures in other areas of your application. “Fly two mistakes high” is an old adage in the radio control airplane hobby. It means, fly high enough so that if you make a mistake, you can continue flying with room to still make mistakes. In his session at 18th Cloud Expo, Lee Atchison, Principal Cloud Architect and Advocate at New Relic, will discuss how this same philosophy can be applied to highly scaled applications, and can dramatically increase your resilience to failure.
SAP is the world leader in enterprise applications in terms of software and software-related service revenue. Based on market capitalization, we are the world's third largest independent software manufacturer. Harness the power of your data and accelerate trusted outcome-driven innovation by developing intelligent and live solutions for real-time decisions and actions on a single data copy. Support next-generation transactional and analytical processing with a broad set of advanced analytics - run securely across hybrid and multicloud environments.
Founded in 2002 and headquartered in Chicago, Nexum® takes a comprehensive approach to security. Nexum approaches business with one simple statement: “Do what’s right for the customer and success will follow.” Nexum helps you mitigate risks, protect your data, increase business continuity and meet your unique business objectives by: Detecting and preventing network threats, intrusions and disruptions Equipping you with the information, tools, training and resources you need to effectively manage IT risk Nexum, Latin for an arrangement by which one pledged one’s very liberty as security, Nexum is committed to ensuring your security. At Nexum, We Mean Security®.