Sunday, March 31, 2013

Fast Input/Output in C




This is my first post and I would begin it with one of the very crucial and overlooked segment of a program.
i.e the IO(Input/Output).
Most of us are content with using scanf,printf,getc,putchar in C .
For programs with large number of numerical inputs(ints,long) in C we often use scanf("%d") which is even slower than taking input as a String using scanf("%s")  or gets() and then converting the number using atoi function.

Almost everyone has never heard of the function getchar_unlocked()  in C.

  •  getchar_unlocked() is a macro provided by C and this function has much less overhead as compared with the getchar().
  • getchar_unlocked() is not thread safe and does not have many safety checks.Although it is not recommended to use a function which is not thread safe,it can be safely used if we just need to take inputs and don't have a multi threaded program.(usually in the programming competitions where speed is the primary concern).
Below is  the code snippet which demonstrates how to use the getchar_unlocked() for developing fast Input solutions for reading int,long etc.

PS: I have used the inline keyword here,Inlining is done to request the compiler to replace the source code of the function at the places its being called,thereby it will become a bit faster and optimized as there wont be an overhead for allocating the stack separately for the function.



Normally Printf is quite fast for outputs,however for writing Integer or Long Outputs,the below function is a tad bit faster. Here we use the putchar_unlocked() method for outputting a character which is similar thread-unsafe version of putchar() and is faster.








1 comment:

  1. In case anyone is wondering what I mean by
    rev = (rev<<3) + (rev<<1) + N % 10; its just a optimised way of writing
    rev=(rev*10)+(N%10);

    ReplyDelete