benfred / py-spy

Sampling profiler for Python programs
MIT License
12.53k stars 414 forks source link

How could I view the average time taken for a function? #519

Closed roger12023 closed 2 years ago

roger12023 commented 2 years ago

Im using it with speedscope, It took me a day to check the documentations and try out some experiment to fail to get the average time per functions, in the graph as below there are two functions, since the time taken is for the purple/green functions varies over time, it would be nice to know what is the average time cost for functions.

Please shed me some light over it, I look forward to your replies. Thanks

image

Jongy commented 2 years ago

py-spy is a sampling profiler. It doesn't trace your program and it doesn't know "how much time" things takes. The resulting profile of py-spy gives you the relative distribution of samples spent in different areas of your code (and logically, the relative distribution of time). But if a function takes, say, 10% of a profile of 10 seconds, you can't know if it ran for one full second, or if it ran a million times during that one second.

If you want to get "how much time" you can use a tracing profiler like cProfile, which can measure the number of executions of a function, and the cumulative duration, etc.

roger12023 commented 2 years ago

I got it, thanks

py-spy is a sampling profiler. It doesn't trace your program and it doesn't know "how much time" things takes. The resulting profile of py-spy gives you the relative distribution of samples spent in different areas of your code (and logically, the relative distribution of time). But if a function takes, say, 10% of a profile of 10 seconds, you can't know if it ran for one full second, or if it ran a million times during that one second.

If you want to get "how much time" you can use a tracing profiler like cProfile, which can measure the number of executions of a function, and the cumulative duration, etc.

Thanks Jongy for the extensive explanation.

Jongy commented 2 years ago

You're welcome :)