5

What is the cheapest way to roundup() or ceil() to multiple of 1000?

For example if cheapest way to roundup is implemented in the ceil function:

function ceil(uint a, uint m) returns (uint) {
    //some cheap roundup to muliple function
}

then it is expected that:

  • ceil(123456,1000) == 124000
  • ceil(1,1000) == 1000
  • ceil(0,1000) == 0
  • ceil(123000,1000) == 123000
10

Here's one solution:

contract Ceil {
    function ceil(uint a, uint m) constant returns (uint ) {
        return ((a + m - 1) / m) * m;
    }

    // To measure gas
    function ceil1(uint a, uint m) returns (uint ) {
        return ((a + m - 1) / m) * m;
    }
}

And testing for the correct results:

> ceil.ceil(123456, 1000)
124000
> ceil.ceil(1,1000)
1000
> ceil.ceil(0,1000)
0
> ceil.ceil(123000,1000)
123000

To measure the gas, I've created ceil1(...) and sent a transaction:

> ceil.ceil1(123456, 1000, eth.accounts[0], {
   from:web3.eth.accounts[0], 
   data: ceilCompiled.Ceil.code,
   gas: 1000000
});
"0xeac6bb84ba5a1703ee3a762cb392f1793adf550906b6112e441928c0ea288f53"
...
> debug.traceTransaction("0xeac6bb84ba5a1703ee3a762cb392f1793adf550906b6112e441928c0ea288f53")
{
  gas: 21990,
  returnValue: "000000000000000000000000000000000000000000000000000000000001e460",
  structLogs: [{

The gas cost of this calculation is 21,990. This figure would include the default 21,000 gas for sending a regular transaction which gives an incremental gas cost of 990.

When plugging the code into the Online Solidity Compiler at https://chriseth.github.io/browser-solidity/#version=soljson-latest.js, the following gas cost are estimated:

Creation: 69 + 43000
External:
  ceil(uint256,uint256): 275
  ceil1(uint256,uint256): 253
Internal:

So an estimate for the gas cost of ceil1(...) is between 253 and 990.

3

I don't know if this is the cheapest, but one of solutions I have managed to invent is this one:

function ceil(uint a, uint m) returns (uint r) {
    return (a + m - 1) / m * m;
}

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.