Home > OS >  Showing time interactively for a line of code
Showing time interactively for a line of code

Time:08-11

I am running a code and it takes a little bit of time to run. Now I want to use some interactive type of thing like while running the code, it will show some like "time spent on this line: 5 sec->6 sec...".

Let me explain properly. Suppose f is a function for which I need the counter and returns x, and let counter is a function which interactively prints the time.

So it will be:

x = counter(f())

After it starts running, in console/cmd it will print like this:

time spent on f(): t sec

Only it t will change automatically, like, 1, then 2, then 3 etc. When the function run is complete, it will print:

Total time spent on f(): T sec

I searched online and could not find anything like this. I tried asyncio, but could not find any solution. Can anyone tell what is the possible ways to do this. Thanks.

CodePudding user response:

This wouldn't be a general solution, but it would work in certain cases:

Write a function decorator that uses concurrent.futures to spin up an async thread/process that periodically prints to stdout as the decorated function runs. When the decorated function completes, capture its return value, print out total elapsed time, and return that return value.

That being said, it would be much easier just to use simple logging statements or an existing flamegraph analyzer like pyflame or flameprof to accomplish the same.

  • Related