1

I implemented a dynamic array in solidity for my own use. The following is my implementation. I can get the accurate gas cost of each function call by clicking the debug message in the console of remix. However, manually getting gas costs is tedious and I'm thinking if I can write another solidity script to get the gas cost of my function call. For example, I want to get the gas cost of consecutively calling push API for 10000 times. The x-axis should be the number of API calls, and the y axis should be the cumulative gas cost up to i API calls. Is there any built-in function in solidity to help me do that?

// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; contract Array { // Several ways to initialize an array uint[] public arr; uint[] public arr2 = [1, 2, 3]; // Fixed sized array, all elements initialize to 0 uint[10] public myFixedSizeArr; function get(uint i) public view returns (uint) { return arr[i]; } // Solidity can return the entire array. // But this function should be avoided for // arrays that can grow indefinitely in length. function getArr() public view returns (uint[] memory) { return arr; } function push(uint i) public { // Append to array // This will increase the array length by 1. arr.push(i); } function pop() public { // Remove last element from array // This will decrease the array length by 1 arr.pop(); } function getLength() public view returns (uint) { return arr.length; } function remove(uint index) public { // Delete does not change the array length. // It resets the value at index to it's default value, // in this case 0 delete arr[index]; } function examples() external { // create array in memory, only fixed size can be created uint[] memory a = new uint[](5); } } 

1 Answer 1

2

You can use msg.gas and store the value to a variable, when the contract is executed the gas amount will be stored.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help. This method works. I got an array of gas cost. However, how can I export that array of gas cost so that I can plot a graph.
you can checkout github.com/ConsenSys/surya it provides inspection with your functions in contracts if that's what you're asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.