What is the best way to perform line profiler in Python to achieve this?

py-spy is a sampling profiler for Python that can track the execution of Python programs, including visualizing call stacks and time spent on specific lines.

Install py-spy:

pip install py-spy

Run py-spy to attach to a running Python process and view the profiling information:

py-spy top --pid <PID>

Use the py-spy graphical interface to view the line-by-line breakdown of execution.

This solution provides a real-time, interactive way to monitor and profile Python code with a GUI, offering insight into execution time at a fine-grained level.