sumerc / yappi

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

Print only `N` lines of result #171

Open NicolasMICAUX opened 3 months ago

NicolasMICAUX commented 3 months ago

I cannot find an option to not print all the lines, but say only the first 500.

I'm trying:

stats = yappi.get_func_stats().sort("ttot")
# keep only the first 500 lines
stats = stats[:500]  # BUT THIS CONVERTS stats TO A LIST, SO print_all WILL NOT WORK
stats.print_all()

The solution is actually quite easy, something like this:

def print_all(
    self,
    out=sys.stdout,
    columns={0: ("name", 36), 1: ("ncall", 5), 2: ("tsub", 8), 3: ("ttot", 8), 4: ("tavg", 8)},
    N: int = None,
):
    """
    Prints all of the function profiler results to a given file. (stdout by default)
    """
    if self.empty():
        return

    for _, col in columns.items():
        _validate_columns(col[0], COLUMNS_FUNCSTATS)

    out.write(LINESEP)
    out.write(f"Clock type: {self._clock_type.upper()}")
    out.write(LINESEP)
    out.write(f"Ordered by: {self._sort_type}, {self._sort_order}")
    out.write(LINESEP)
    out.write(LINESEP)

    self._print_header(out, columns)
    for i, stat in enumerate(self):
        if N is not None and i >= N:
            break
        stat._print(out, columns)