Skip to content

Instantly share code, notes, and snippets.

@nickfrosty
Last active January 18, 2025 06:58
Show Gist options
  • Save nickfrosty/62edb20f0a789db5a0525b9e7a353e00 to your computer and use it in GitHub Desktop.
Save nickfrosty/62edb20f0a789db5a0525b9e7a353e00 to your computer and use it in GitHub Desktop.
Calculate and log the consumed compute units for a block of code in a Solana program
/// Calculate and log the consumed compute units for a block of code
///
/// Note: Syscalls cost [100 CU](https://github.com/anza-xyz/agave/blob/d88050cda335f87e872eddbdf8506bc063f039d3/program-runtime/src/compute_budget.rs#L150)
/// It is also not accessible via a program: https://solana.stackexchange.com/questions/19024/how-can-a-rust-program-get-access-to-the-syscall-base-cost-value
#[macro_export]
macro_rules! compute_usage_cost {
// Log with a custom message
(
$msg:expr => $($tt:tt)*
) => {
{
let initial = sol_remaining_compute_units();
{ $($tt)* };
let diff = initial-sol_remaining_compute_units();
msg!("Consumed CUs: {} --> {}", $msg, diff);
diff
}
};
// Log without a custom message
($($tt:tt)*) => {
{
let initial = sol_remaining_compute_units();
{ $($tt)* };
let diff = initial-sol_remaining_compute_units();
msg!("Consumed CUs: {}", diff);
diff
}
};
}
compute_usage_cost!("with a message" => {
require!(new_count <= u64::MAX, CustomError::Default);
ctx.accounts.counter.count = new_count;
});
let diff = compute_usage_cost!({
require!(new_count <= u64::MAX, CustomError::Default);
});
msg!("diff value: {}", diff);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment