This wouldn't be a problem if the CPU-intensive code would be placed inside an extrinsic since we could benchmark it and get the accurate weight for the code.

But the problem is that we cannot benchmark a hook inside a pallet(e.g. We cannot benchmark the on_initialize hook AFAIU).

If the code inside the hook is intensive because of reads/writes from the runtime we can use the T::DbWeight::get().reads_writes(reads, writes) function which calculates the weight it takes for the specified number of reads&writes.

But what can I do if the code is actually CPU-heavy?

1 Answer 1


There is nothing stopping you from benchmarking the on_initialize hook.
The manual Read/Write stuff is just an approximation, so benchmarking it is better,
Since its a Hook and not a Call, you need to use the syntax for arbitrary code execution:

on_initialize {
    // Setup code
}: {

You can see this being done in the Lottery pallet. The generated weight functions are then used here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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