Fast way of updating posebone matrix in global space

I’m working on a tool that snaps FK bones to the corresponding IK bones. The code for the arm looks something like this:

matchPoseRotation(uparmFk, uparmIk)
updatePose(uparmFk)
matchPoseRotation(loarmFk, loarmIk)
updatePose(loarmFk)
matchPoseRotation(handFk, handIk)

The matchPoseTransform function sets the posebone’s base matrix (posebone.matrix_basis), and uses its parent’s matrix in global space (posebone.parent.matrix). Therefore we must update the parent’s matrix before doing the calculations for the child. One can do that by forcing a scene update, e.g. by defining

def updatePose(posebone):
    deps = bpy.context.evaluated_depsgraph_get()
    deps.update()

or the old-fashioned way:

def updatePose(posebone):
    bpy.ops.object.posemode_toggle()
    bpy.ops.object.posemode_toggle()

These methods work, but the problem is that they update the entire scene, and since I call updatePose many times this takes a very long time. Is there a faster way of doing it? I don’t need to update the entire scene, or even the armature, but only the specified posebone.

rigify using this method

bpy.context.view_layer.update()

and in my experience more fast than evaluated_depsgraph_get and apply visual transform

Thank you, but it didn’t make a difference. Transferring a 250 frame animation from FK to IK took 460 seconds with both update methods. The view-layer update didn’t change the cursor though, so one could follow the progress better.

It feels very wasteful to update the entire scene when I only need the matrix of the immediate parent. I will try to calculate that manually and skip the updates altogether (update is still needed for each frame change of course).

As a comparison, if I skip the updates altogether the transfer took 269 seconds (compared to 460), but the result is less accurate. So the script spends 42% of the time doing scene updates.