Python耗时统计-可嵌套-生成Timeline-chrome://tracing/预览


本文演示了如何用chrome://tracing查看python嵌套代码的耗时成分

一.效果

Python耗时统计-可嵌套-生成Timeline-chrome://tracing/预览-LMLPHP

二.代码

import time
import os
import threading
import queue

def singleeton(cls):
    '''
    单例
    '''
    instance={}
    def _singleton(*args, **kwargs):
        if cls not in instance:
            instance[cls] = cls(*args, **kwargs)
        return instance[cls]
    return _singleton

@singleeton
class TimeLineContext(object):
    def __init__(self,filepath="time.json") -> None:
        self.fo = open(filepath, "w")
        self.stack=[""]
        self.first=True
        self.fo.write("[\n")

    def __del__(self):
        print("TimeLineContext Close")
        self.fo.write("]\n")
        self.fo.close()

    def push_back(self,title):
        self.stack.append(title)

    def pop(self):
        self.stack.pop()

    def back(self):
        return self.stack[-1]

    def write(self,message):
        if not self.first:
            self.fo.write(",\n")
        self.first=False
        self.fo.write(message)

class TimeLine:
    def __init__(self, title):          
        self.ctx= TimeLineContext() 
        self.title = self.ctx.back()+"/"+title 
        self.ctx.push_back(self.title)

    def __enter__(self):
        self.beg= time.time()*1000*1000
        self.pid=os.getpid()
        self.tid=threading.current_thread().ident
        self.ctx.write("{"+f'"name": "{self.title}","cat": "PERF", "ph": "B", "pid": {self.pid}, "tid": {self.tid}, "ts": {self.beg}'+"}")

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.end=time.time()*1000*1000
        self.ctx.write("{"+f'"name": "{self.title}","cat": "PERF", "ph": "E", "pid": {self.pid}, "tid": {self.tid}, "ts": {self.end}'+"}")
        self.ctx.pop()

if __name__ == "__main__":
    with TimeLine(f"e2e"):
        for i in range(5):
            with TimeLine(f"iter:"):
                for j in range(2):
                    with TimeLine(f"block:"):
                        time.sleep(0.2)
                    with TimeLine(f"branch:"):
                        time.sleep(0.1)
                time.sleep(0.1)
                with TimeLine(f"demo:"):
                    time.sleep(0.1)
                            
        with TimeLine(f"end"):
            time.sleep(0.1)                    
03-30 20:03