A warrior never surrenders, A warrior never quits..


Monday, December 1, 2008

fastest i/o methods

Almost all the problems involve some kind of input and output processing. Unless your code is of O(n^2) or above, more than 70% of the running time goes for IO processing. So it is important to perfrom these operation efficiently in order to make the entire program efficient. here are some tips regarding input and output...
1. More overloaded a function the more time it takes
It means if you use overloaded function or stream opreator then it will take more time than an ordinary function, in short cin is slower than scanf() which in turn is slower than gets()
2. Input and output usually involves peripheral hardwares which make them slow.
If you are taking input from file then its ok otherwise you have to use keyboard which can slow down the speed not because you cant type fast(even thats also true) but because it has to check the buffer of keyboard and same in case output.
3. String and character arrays are easy to handle in case of input and output because the compiler just has to use them exactly as they are. Int, Long and Floats have to be transformed before printing or before storing.

Here is a hierarchy of the methods to take the input:
> fread() or read() system call
> gets() or getchar()
> scanf()
> cin>>
these are the methods in the increasing order of processing time with fread() is the fastest and cin being the slowest.

similarly you can figure out for the output:
> fwrite() or write()
> puts()
> printf()
> cout<<

now choose any one option according to the situation. Choose from the bottom if you want good looking but relatively slower code and choose from the top if you want complex but faster code... as always choice is yours :)
happy coding

2 comments:

vaibhav said...

informative.. besides some spelling errors.. :)

Eps!lon said...

:P I will remember it... thanks