chriskohlhoff / asio

Asio C++ Library
http://think-async.com/Asio
4.97k stars 1.22k forks source link

Count poll and run with potentially one less branch #1525

Open Andersama opened 2 months ago

Andersama commented 2 months ago

Note: The same condition can be expressed with a single statement.

n += (~n > 0); or n += (~n != 0);

However this introduces an additional ~ operation for every loop.

An equivalent but more convoluted loop counts down:

  size_t inverted_n = (std::numeric_limits<size_t>::max)();
  while (do_one(INFINITE, this_thread, ec))
    inverted_n -= (inverted_n != 0); //count "down" backwards from the max
  return ~inverted_n; //so we can flip the result without doing ~'s at each step

Ultimately, each method should be checking the non-zero flag, so outside additional few nanoseconds worth of instructions they should be equivalent, main point is to remove an unnecessary branch. I've only modified the related the windows file as an example, and I'm not sure where the other implementation exists.