How to measure cpu usage (as a percentage) of a single code line in Python?

Viewed 129

I need to know how much this particular line of code loads my cpu when whole program is executed:

cap.set(cv.CAP_PROP_POS_FRAMES,random_frame)

This line is part of a certain program. But I'm only interested in how this particular line loads the cpu. I don't know exactly how to measure it.

To be more precised, this is my full code:

import cv2 as cv
import random

cap = cv.VideoCapture('file_name.avi')

random_frame = random.randint(1,99999)

cap.set(cv.CAP_PROP_POS_FRAMES,random_frame)

ret, frame = cap.read()

cv.imshow("random_frame",frame)

while cap.isOpened():
    if cv.waitKey(1) == ord('q'):
        break
    
cap.release()
cv.destroyAllWindows()

Windows 7 operating system

1 Answers
import multiprocessing as mp
import psutil
import random
import cv2 as cv
import random

cap = cv.VideoCapture ('file_name.avi')

random_frame = random.randint (1, 99999)


def monitorFunction():
  cap.set (cv.CAP_PROP_POS_FRAMES,random_frame)

def monitor (target):
    worker_process = mp.Process(target=target)
    worker_process.start()
    p = psutil.Process(worker_process.pid)

    # log cpu usage of `worker_process` every 10 ms
    cpu_percents = []
    while worker_process.is_alive():
        cpu_percents.append(p.cpu_percent())
        time.sleep(0.01)

    worker_process.join()
    return cpu_percents

cpu_percents = monitor(target=monitorFunction)
print (cpu_percents)

This should work.

Related