0

I'm using this contract to emit events about the gas a function uses:

contract GasDebug {
     event LogGas(uint256 gas);

     modifier debugGasUsed() {
         uint256 startGas = gasleft();
         _;
         uint256 endGas = gasleft();
        LogGas(startGas - endGas);
     }
}

And I'm testing the storage of a uint256 like so:

contract TestGasDebug is GasDebug {

    uint256 store;

    function test_1(uint256 _a) 
        debugGasUsed
    {
        store = _a;
    }
}

Which I would expect to give me the result of 20000 but instead the event gives the value of 20021. Where is the extra 21 units of gas coming from?

  • 3 gas units for the subtraction, 2 for each get-gas operation, 3 for each save to memory, so at least 200013. – goodvibration May 7 '18 at 18:11
  • The subtraction is actually after the values are stored, so it's not that. I assume there's some cost to the opcode gasleft() corresponds to. There's also an assignment to store the value in memory. – user19510 May 7 '18 at 18:12
  • MSTORE is 3, and GAS is 2, so that's 5... you'd have to look at the compiled bytecode to spot where the rest is. Perhaps a bit of math and PUSHes to figure out the location in memory to store the result. I assume a JUMP (unless modifiers are inlined?) to go to test_1 and a JUMP to get back. – user19510 May 7 '18 at 18:14
  • @goodvibration Regarding your edit, only one of the get-gas operations would count (the first already takes into account the cost of the GAS opcode), only one of the writes to memory (because the second happens after the GAS opcode), and no subtraction (because that too happens after the GAS opcode). – user19510 May 7 '18 at 18:26
  • @smarx: I made a quick analysis in the answer below, based on the EVM yellow paper. I might have over or under counted something, so feel free to edit if you find anything. Thanks. – goodvibration May 7 '18 at 18:28
1

From debugging in Remix, here are the opcodes that happen after the first GAS opcode. Gas costs come from https://github.com/djrtwo/evm-opcode-gas-costs/blob/master/opcode-gas-costs_EIP-150_revision-1e18248_2017-04-12.csv. Compiler version was 0.4.23+commit.124ca40d.Emscripten.clang with optimizations turned off:

  • SWAP2 - 3
  • POP - 2
  • DUP3 - 3
  • PUSH1 - 3
  • DUP2 - 3
  • SWAP1 - 3
  • SSTORE - 20000 (for zero to non-zero)
  • POP - 2
  • GAS - 2

Total: 20021

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.