How to profile CPU usage of a Python script? : <p>Ideally what I want is to record the CPU usage of a Python script that is executing a deep neural net <a href="https://keras.io/" rel="noreferrer">Keras</a> model. I'm looking for the CPU equivalent of <a href="https://pypi.python.org/pypi/memory_profiler" rel="noreferrer">memory_profiler</a>, which provides the memory consumption of a process.</p>

<p>I have looked at using <a href="https://github.com/giampaolo/psutil" rel="noreferrer">psutil</a> (suggested in <a href="https://stackoverflow.com/questions/44637844/cpu-usage-of-python-script">this answer</a>) which would indicate my script could contain some variant of</p>

<pre><code>p = psutil.Process(current_pid)
p.cpu_percent()
</code></pre>

<p>but the problem is the important function call I really want to capture the effect of would be the inference stage of the model</p>

<pre><code>model.predict(x_test)
</code></pre>

<p>and if I run psutil before/after this step the CPU usage recorded won't be a true reflection of the CPU usage of the process.</p>

<p>So then I was thinking could I use something like top/htop to log the CPU usage of the script to some file, capturing the fluctuating CPU usage while the process 
is running, and then calculate an average (or something similar) after the fact. The issue I see with this, however, is don't I need to know the PID to utilise top,
so how can I use top to monitor the script before it is executed (and hasn't even been assigned a PID)?</p>

<p>I can see <a href="https://stackoverflow.com/questions/582336/how-can-you-profile-a-script/582337#582337">this highly-ranked answer</a> suggests 
cProfile which gives the running time of functions within a script. Although this isn't exactly what I want I do notice that it returns
the total number of CPU seconds, which would at least let me compare CPU usage in that regard.</p>
