How to use enif_consume_timeslice to calculate percent?

I’m trying to figure out how to use enif_consume_timeslice, and I don’t feel like I’m understanding it.

while (true) {
  // ... do expensive work here, return result if computation completes

  if (enif_consume_timeslice(env, percent)) {
    return enif_schedule_nif(...);

Is this how this works? How am I supposed to calculate percent? Should I literally time how long each loop iteration takes and divide that by one millisecond?

1 Like

It is to be used as a best effort guesstimate. What you want to avoid is the expensive work taking seconds without re-scheduling. If you don’t have a good way of knowing how much time the “do expensive work” can take, then it might be a better idea to just run it on a dirty CPU scheduler.


lets say I do know how long it will take. how do i translate that knowledge into the percent value?

100% is 1ms, so 1% would be 10µs.

If the time something takes is less than 10µs, then you need to run x iterations for each percentage that you consume.

1 Like