Python如何快速定位最慢的代码?太优雅了~
import timedef slow_function():time.sleep(2)return "Slow function finished."def fast_function():return "Fast function finished."start_time = time.time()print(slow_function())print(f"Slow function took {time.time() - start_time} seconds")start_time = time.time()print(fast_function())print(f"Fast function took {time.time() - start_time} seconds")
import timedef slow_function():time.sleep(2)return "Slow function finished."def fast_function():return "Fast function finished."def main():print(slow_function())print(fast_function())if __name__ == "__main__":main()
pyinstrument your_script.py
pyinstrument 的使用案例
import timedef process_data(data):time.sleep(1) # Simulate a time-consuming operationreturn [d * 2 for d in data]def main():data = list(range(10))result = process_data(data)print(result)if __name__ == "__main__":main()
pyinstrument your_script.py
process_data 函数中的 time.sleep(1) 是最耗时的部分。通过这份报告,我们可以清楚地看到代码中的瓶颈,从而进行针对性的优化。pyinstrument 的优势
import asyncioasyncdef slow_function():await asyncio.sleep(2)return "Slow function finished."async def fast_function():return "Fast function finished."async def main():print(await slow_function())print(await fast_function())if __name__ == "__main__":asyncio.run(main())
pyinstrument your_script.py小结
目前,对编程、职场感兴趣的同学,大家可以联系我微信:golang404,拉你进入“程序员交流群”。
资料包含了《IDEA视频教程》、《最全python面试题库》、《最全项目实战源码及视频》及《毕业设计系统源码》,总量高达650GB。全部免费领取!全面满足各个阶段程序员的学习需求!