标签: Python

  • Python multiprocessing RawArray no disk space, or very slow

    It seems that Python writes to /tmp on linux base os when allocating python.multiprocessing.sharedctypes.RawArray. If the disk space on that path is not sufficient, “no disk space” error occurs.
    The solution is to change the default TMPDIR environment, using one of below methods:

    • bash: export TMPDIR='/the/new/path'
    • bash: TMPDIR=/the/new/path python3 your_script.py
    • python: os.environ['TMPDIR']='/your/new/path'

    By the way, using /dev/shm as the tmpdir enhances performance to me~

  • Python multiprocessing 并行化原则

    处理multiprocessing解决棘手的并行问题时,遵循以下策略:

    • 把工作拆分成独立单元;
    • 如果每项工作所花的时间是可变的,那就考虑随机化工作的序列;
    • 对工作队列进行排序,首先处理最慢的任务可能是一个最有用的策略(平均而言);
    • 对于细小琐碎的任务,考虑将他们合并分块(chunk),这样能有效减小fork/join通信开销;
    • 任务数量与物理CPU数量保持一致;

    部分摘自 <High Performance Python> (by Micha Gorelick, Ian Ozsvald)

  • Python Facade模式 门面模式

    门面模式(Facade Design Pattern, 一称外观模式)属于结构型设计模式。结构型设计模式描述如何将对象和类组合成更大的结构。除了门面模式外,还有适配器模式、桥接模式、装饰器模式,他们都属于结构型设计模式。
    W3sDesign_Facade_Design_Pattern_UML.jpg
    这个模式有3个主要部分:

    • 门面(Facade):将一组复杂倒置系统封装起来,从而为外部世界提供一个舒适的外观;
    • 子系统(Subsystem):一些不同的子系统(上图中的Class1, Class2, Class3…),这些子系统让整个系统混杂在一起,难以使用;
    • 客户端(Client):通过门面提供的简单易用的接口,与门面进行交互,而避免接触复杂的各种子系统.

    案例

    假设你要在家中举办一场婚礼,必须预订一家酒店,与餐饮人员交代菜品、与布置人员敲定场地布置细节^%&*……头大的方法是自己安排这一切,或者可以去找一个婚礼管家,让他/她为你安排这一切。

    class EventManager:
      def arrange(self):
        self.hotelier = Hotelier()
        self.hotelier.bookHotel()
    
        self.florist = Florist()
        self.florist.setFlowerRequirements()
    
        self.caterer = Caterer()
        self.caterer.SetCuisine()
    
        self.musician = Musician()
        self.musician.setMusicType()
    

    上述Hotelier(), Florist(), Caterer(), Misicial()就是各种复杂的子系统。然后,对于你自己来说,只要这样就能轻松搞定:

    class You:
      def askEventMeneger(self):
        em = EventManager()
        em.arrange()
    
    you = You()
    you.askEventManager()
    

    最少知识原则

    最少知识原则指导我们减少对象之间的交互,它意味着:

    • 在设计系统时,对于创建的每个对象,都应该考察与之交互的类的数量以及交互的方式;
    • 避免许多紧密耦合的类;
    • 如果对系统中的任何一部分进行修改都可能导致系统其他部分被无意改变,这意味着系统退化,应该坚决避免。

    参考文献

    《Python设计模式(第二版)》by Chetan Giridhar

  • pyprof2calltree — Python 性能分析 可视化

    性能分析用cProfile

    python -m cProfile -o output.perf your_script.py --your args
    

    然后可以安装pyprof2calltree

    pyprof2calltree -i output.perf -k
    

    记得系统里要装qcallgrind(windows)或者kcallgrind,不然会打不开生成好的log
    pyprof2calltree.jpg