Member-only story
How to use Buffering to Improve Efficency
When we read and write files on a system, we will often need to define a buffer size to tell the system how many bytes we need to read. When we are doing this, it is important to carefully consider the size of the buffer we choose. Whenever we need to read a file, we need to transfer into kernel mode, which is a context switch that takes a significant amount of time. If we can reduce the number of file reads, we can reduce the number of transfers into kernel mode, and therefore, reduce the execution time of our programs.
Consider for example reading utmp records in order to determine who is currently logged onto a system. If we were to approach this problem without considering buffers, we would read a single record from the utmp file at a time, and print the results, as shown below.
With this approach, we read a single record, process it through the show_info function, then read another record, until we reach the end of the file. Doing this means we need to do a number of reads equal to the number of records in the utmp file.
If we want to make this code more efficient, we can read from the utmp file using a buffer. In this example, we will crate a buffer that can hold 16 utmp structs. Doing this will cut the number of system reads required by a factor of 16, which will greatly improve the efficiency of the program.