在每次函数调用后获得准确的 gas 成本
Getting accurate gas cost after each function call
我在 solidity 中实现了一个动态数组供我自己使用。以下是我的实现。我可以通过单击 remix 控制台中的调试消息来获取每个函数调用的准确 gas 成本。然而,手动获取 gas 成本是乏味的,我在想我是否可以编写另一个 solidity 脚本来获取我的函数调用的 gas 成本。例如,我想获取连续调用 push
API 10000 次的 gas 成本。 x 轴应该是 API 次调用的次数,y 轴应该是第 i API 次调用的累计 gas 成本。 solidity 中是否有任何内置函数可以帮助我做到这一点?
// 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);
}
}
您可以使用msg.gas
并将值存储到变量中,当合约执行时,gas 量将被存储。
我在 solidity 中实现了一个动态数组供我自己使用。以下是我的实现。我可以通过单击 remix 控制台中的调试消息来获取每个函数调用的准确 gas 成本。然而,手动获取 gas 成本是乏味的,我在想我是否可以编写另一个 solidity 脚本来获取我的函数调用的 gas 成本。例如,我想获取连续调用 push
API 10000 次的 gas 成本。 x 轴应该是 API 次调用的次数,y 轴应该是第 i API 次调用的累计 gas 成本。 solidity 中是否有任何内置函数可以帮助我做到这一点?
// 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);
}
}
您可以使用msg.gas
并将值存储到变量中,当合约执行时,gas 量将被存储。