forge test includes support for reporting gas usage by method externally with --gas-report.

However, I would like to measure gas usage within a given unit test, which from reading the documentation doesn't appear to be supported (though the Foundry documentation is sometimes thin).

Is there a way to measure gas usage within forge unit tests, ideally via an assert for a section of code in a given block?

2 Answers 2


It is not currently possible to create custom spans for gas reporting in Forge - or rather, Forge does not have a built-in mechanism for this.

The only way you can achieve something similar, is to create your own helper functions that use the gasleft() Solidity built-in.

These two functions are taken from solmate:

contract GasHelpers {
    string private checkpointLabel;
    uint256 private checkpointGasLeft = 1; // Start the slot warm.

    function startMeasuringGas(string memory label) internal virtual {
        checkpointLabel = label;

        checkpointGasLeft = gasleft();

    function stopMeasuringGas() internal virtual {
        uint256 checkpointGasLeft2 = gasleft();

        // Subtract 100 to account for the warm SLOAD in startMeasuringGas.
        uint256 gasDelta = checkpointGasLeft - checkpointGasLeft2 - 100;

        emit log_named_uint(string(abi.encodePacked(checkpointLabel, " Gas")), gasDelta);

The function emits an event with the gas used. To see the output of the events you must run your tests with at least double verbosity: forge test -vv.

  • gasleft() is exactly what I needed, thank you!
    – jnic
    Jul 25, 2022 at 17:33

You can use forge snapshot --match-test test_name to run test and it will produce a gas-snapshot file where you can see gas usages

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.