我可以在python模块上运行line_profiler吗?
我有一个名为my_module的模块,其结构如下我可以在python模块上运行line_profiler吗?,python,python-unittest,line-profiler,Python,Python Unittest,Line Profiler,我有一个名为my_module的模块,其结构如下 . └── my_module ├── main.py └── test.py 这里,我使用python-myu module.test来运行测试,因为它使用相对导入 那么如何在模块上运行line_profiler、memory_profiler?(可以是pytest) 以下是我尝试过的 第一种方法 第二种方法 您可以将line\u profiler与unittest.TestCase一起使用。 只需将print_stats移动
.
└── my_module
├── main.py
└── test.py
这里,我使用python-myu module.test来运行测试,因为它使用相对导入
那么如何在模块上运行line_profiler、memory_profiler?(可以是pytest)
以下是我尝试过的
第一种方法
第二种方法
您可以将
line\u profiler
与unittest.TestCase
一起使用。
只需将print_stats
移动到TestCase的tearDownClass
import unittest
import line_profiler
profiler = line_profiler.LineProfiler()
class PageTester(unittest.TestCase):
@profiler
def test_abc(self):
print("abc")
#profiler.print_stats()
@profiler
def test_def(self):
self.test_abc()
@classmethod
def tearDownClass(cls):
profiler.print_stats()
if __name__ == "__main__":
unittest.main(module='page.test')
输出是预期的:
abc
abc
Timer unit: 1e-06 s
Total time: 1.3e-05 s
File: /root/page/test.py
Function: test_abc at line 10
Line # Hits Time Per Hit % Time Line Contents
==============================================================
10 @profiler
11 def test_abc(self):
12 2 13.0 6.5 100.0 print("abc")
Total time: 9e-06 s
File: /root/page/test.py
Function: test_def at line 15
Line # Hits Time Per Hit % Time Line Contents
==============================================================
15 @profiler
16 def test_def(self):
17 1 9.0 9.0 100.0 self.test_abc()
您的代码示例是错误的。什么是foo.lprof
?我更新了问题,它应该是空的。我认为你的if
语句是错误的——应该是if\uuuuuuuuu name\uuuuu==“\uuuuuu main\uuuuu”:
import unittest
import line_profiler
profiler = line_profiler.LineProfiler()
class PageTester(unittest.TestCase):
@profiler
def test_abc(self):
print("abc")
#profiler.print_stats()
@profiler
def test_def(self):
self.test_abc()
@classmethod
def tearDownClass(cls):
profiler.print_stats()
if __name__ == "__main__":
unittest.main(module='page.test')
abc
abc
Timer unit: 1e-06 s
Total time: 1.3e-05 s
File: /root/page/test.py
Function: test_abc at line 10
Line # Hits Time Per Hit % Time Line Contents
==============================================================
10 @profiler
11 def test_abc(self):
12 2 13.0 6.5 100.0 print("abc")
Total time: 9e-06 s
File: /root/page/test.py
Function: test_def at line 15
Line # Hits Time Per Hit % Time Line Contents
==============================================================
15 @profiler
16 def test_def(self):
17 1 9.0 9.0 100.0 self.test_abc()