c++ - Why is getchar_unlocked() faster than alternatives? -
i know how code works not find why code faster other i/o methords???
int read_int() { char c = getchar_unlocked(); while(c<'0' || c>'9') c = getchar_unlocked(); int ret = 0; while(c>='0' && c<='9') { ret = 10 * ret + c - 48; c = getchar_unlocked(); } return ret; }
scanf("%d\n", &x) has parse format string , lock stream before , after reading.
std::cin >> x might locking too, , might have sync stdin, , might need go through abstraction layers.
with above, 1 type of input parsing (so no need parse format string , decide based on that) , importantly, don't lock stream.
locking streams mandated posix, , glibc uses recursive mutexes prevent multiple threads (even in single-threaded environment) accessing stdin file simultaneously (which corrupt it). these mutexes quite expensive (your read_int should several (fivish?) times faster scanf("%d",&x)).
regarding implementation, apart fixing magic number issue, should detect failures in getchar_unlocked , report failures through separate channel -- e.g., returning parsed integer through passed-in pointer , using return status error reporting.
if want thread safety, can still use getchar_unlocked speedup compared getchar, have flockfile(stdin); , funlock(stdin); @ beginning , end (respectively) of read_int function.
Comments
Post a Comment