0

I want to get execution cost every loop when function addData() was call. The solidity remix show execution cost when program run finish. How to show execution cost in each loop?

contract Test_loop {

    uint256 number;

    function testLoop() public{
        uint256 i=0;
        uint256 cnt=0;

        for(i;i<100;i++) {
            cnt++;
            
            addData(cnt);
            console.log(cnt);
        }
    }

    function addData(uint256 _number) public{
 
      number = _number;
 
    }
}
1
  • Not sure if there is a tool for that. Besides Remix Hardhat support gas reporting 'out of the box'. Here is the command REPORT_GAS=true npx hardhat test, but should also show you a total gas cost.
    – Gleichmut
    Jan 25 at 7:49

2 Answers 2

1

You can use the gasleft() function to check how much gas is left after each operation. Subtracting this from the gas you had before the operation gives you the amount of gas used.

    function testLoop() public{
        for (uint i = 0; i < 100; i++) {
            uint256 gasBefore = gasleft();
            addData(cnt);
            uint256 gasUsedForOperation = gasBefore - gasleft();
        }
    }

1
  • Nice, I never even saw that function before.
    – Sky
    Feb 1 at 9:18
0

The only way to do anything remotely similar to that is to go to Remix debugger mode. There you can see the gas cost of each individual step.

However, that might be a bit too complex to do.

I myself usually take the end gas_price and approximate from that.

Example for your case:

gas_price = 89631 gas
basic_transaction_cost =  21000 gas
number of steps in the loop = 100

step_cost = (89631 - 21000)/100
step_cost = 686 gas

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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