本文主要是介绍Python耗时统计-可嵌套-生成Timeline-chrome://tracing/预览,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Python耗时统计-可嵌套-生成Timeline-chrome://tracing/预览
- 一.效果
- 二.代码
本文演示了如何用chrome://tracing查看python嵌套代码的耗时成分
一.效果
二.代码
import time
import os
import threading
import queuedef 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=Trueself.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=Falseself.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*1000self.pid=os.getpid()self.tid=threading.current_thread().identself.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*1000self.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)
这篇关于Python耗时统计-可嵌套-生成Timeline-chrome://tracing/预览的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!