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?
Best Answer
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:
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
.