ON THIS PAGE

  • My App is slow
  • High CPU Usage with tryGet() in a Tight Loop
  • The Problem
  • The Fixes

My App is slow

High CPU Usage with tryGet() in a Tight Loop

The Problem

If you run:
Python
1while True:
2    queue.tryGet()
tryGet() is non-blocking - it returns immediately whether a frame is ready or not. In a tight loop, this means your program spins as fast as possible, maxing out a CPU core and starving other threads or processes.

The Fixes

a) Add a Small SleepLet the CPU breathe between calls:
Python
1#!/usr/bin/env python3
2import depthai as dai
3import time
4with dai.Pipeline() as pipeline:
5    cam = pipeline.create(dai.node.Camera).build(
6        dai.CameraBoardSocket.CAM_A, sensorFps=19.0
7    )
8    rawQueue = cam.raw.createOutputQueue()
9    pipeline.start()
10    while pipeline.isRunning():
11        rawFrame = rawQueue.tryGet()
12        if rawFrame is not None:
13            print("Got a raw frame")
14        time.sleep(0.001)  # prevents 100% CPU usage
b) Use get() Instead of tryGet()get() blocks until a frame is ready, so no busy looping:
Python
1#!/usr/bin/env python3
2import depthai as dai
3import time
4with dai.Pipeline() as pipeline:
5    cam = pipeline.create(dai.node.Camera).build(
6        dai.CameraBoardSocket.CAM_A, sensorFps=19.0
7    )
8    rawQueue = cam.raw.createOutputQueue()
9    pipeline.start()
10    while pipeline.isRunning():
11        rawFrame = rawQueue.get()
12        print("Got a raw frame")