I’m trying to measure cycle consumption in my canister by taking a simple approach:
- Record
balance_before = ic_cdk::api::canister_balance()
. - Perform some async work (e.g.
call_with_payment128
, external HTTP request, etc.). - Record
balance_after = ic_cdk::api::canister_balance()
. - Compute
cycles_used = balance_before - balance_after
.
This works fine if only one request is in-flight at a time. However, my canister has multiple “threads” running concurrently, each potentially doing its own balance_before/balance_after
measurement. Because they can overlap, the final difference in cycles doesn’t necessarily correspond neatly to just one call. For instance, if two calls measure at nearly the same time, their balance deltas can interfere with each other.
Questions:
- Is there any built-in way (similar to
call_with_payment128
) that can tell me exactly how many cycles a particular call or piece of code consumed, without me doing my own balance diffs? - If not, how do I accurately charge different users or subscribers for cycles in a concurrent environment?
- Is there some canisters examples which already implemented these logic? So I can check