Renz7/Python

Created Fri, 11 Aug 2023 15:27:42 +0000 Modified Tue, 12 Dec 2023 22:00:16 +0000
228 Words

Python

性能监控

  • line_profiler
  • pip install line_profiler
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""

    :Time    : 2023/8/11 15:16
    :Author  : ren
"""
import sys
import time

from line_profiler import line_profiler

profiler = line_profiler.LineProfiler()

count = 1


@profiler
def test():
    global count
    for i in range(100):
        time.sleep(0.01)
        print(count)
        count += 1
    print('finns')


if __name__ <span style="font-weight: bold;" class="mark"> '__main__':
    test()
    profiler.print_stats(sys.stdout)
Timer unit: 1e-09 s

Total time: 1.1958 s
File: /Users/ren/PycharmProjects/pythonProject2/pro_test.py
Function: test at line 18

Line #      Hits         Time  Per Hit   % Time  Line Contents
</span>============================================================
    18                                           @profiler
    19                                           def test():
    20                                               global count
    21       100      36000.0    360.0      0.0      for i in range(100):
    22       100 1194305000.0 11943050.0     99.9          time.sleep(0.01)
    23       100    1341000.0  13410.0      0.1          print(count)
    24       100     116000.0   1160.0      0.0          count += 1
    25         1       5000.0   5000.0      0.0      print('finns')

pympler​、objgraph​、tracemalloc


@pytest.fixture(scope='session', autouse=True)
def session_monkeypatch():
    """
    session monkeypatch
    :return:
    """
    mp = MonkeyPatch()
    mock_log = TGLog("/tmp/test.log", write_stream=True)
    import apps.utils.log_util
    mp.setattr(apps.utils.log_util.log, "debug", mock_log.debug)
    mp.setattr(apps.utils.log_util.log, "info", mock_log.info)
    mp.setattr(apps.utils.log_util.log, "warning", mock_log.warning)
    mp.setattr(apps.utils.log_util.log, "error", mock_log.error)
    yield mp
    mp.undo()

generator

def demo_gen():
	for i in range(10):
    	rcv = yeild i
		print(rcv)