sumerc / yappi

Yet Another Python Profiler, but this time multithreading, asyncio and gevent aware.
MIT License
1.45k stars 73 forks source link

Please add context-manager for easier of use #174

Open alex-ber opened 2 months ago

alex-ber commented 2 months ago

This will be less error-prone for your clients. This is my implementation.

import yappi
import contextlib

@contextlib.contextmanager
def yappi_profiler(stats_file_path, stats_format_type='callgrind'):
    yappi.start()
    try:
        yield
    finally:
        yappi.stop()
        yappi.get_func_stats() \
            .save(stats_file_path, type=stats_format_type)
        yappi.clear_stats()

@contextlib.asynccontextmanager
async def ayappi_profiler(stats_file_path, stats_format_type='callgrind):
    yappi.start()
    try:
        yield
    finally:
        yappi.stop()
        yappi.get_func_stats() \
            .save(stats_file_path, type=stats_format_type)
        yappi.clear_stats()
sumerc commented 1 month ago

I am up for it if you can implement this + some tests around this. There might be some naming changes required as well since there is also get_thread_stats..etc.