Advertisement

fgetc() vs fread()

Started by February 28, 2002 05:20 PM
5 comments, last by LearFox 22 years, 7 months ago
This is a speed/efficiency question specifically for Linux. I''m trying to write a Targa image loaded, currently I''m using fgetc() and noticed that the loader runs *MUCH* faster on Windows than on Linux. Would using fread() be more faster/efficient for Linux?
Tara Milana - WP Entertainmenthttp://wolfpack.twu.net/Comp graphics artist and programmer.
It''s not the function, it''s the library implementation. Still, I think fread would be faster all round because it reads a larger contiguous block (as opposed to reading discrete elements in a loop).

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
Advertisement
Using glibc 2.2.3 (I''m pretty sure at least, I haven''t checked ) to read 4,000,000 bytes (the hard drive I''m using isn''t too fast though ):
fgetc, byte at a time: 363 msfread, byte at a time: 758 msfread, all at once:    22 ms


Look into using BUFSIZE, or BUF_SIZE or something like that when you read data. I believe its in stdio.h for linux. It''s the optimised buffer size to read and write data (eg. using fread). Using it, you get the fastest possible data retrieval rate. Or so I''m told. =)
It may be the function-call overhead from fgetc() that is slowing you down. Try using getc(), it''s a macro.
I''d like to thank everyone for their responses.

Jeff, getc() produced the same result as fgetc(). No
major improvements unfortunatly.

I did some more tests, and it agrees, fread() is roughly
10 times faster. Using the optimized buffer size did
not help, simply reading the entire tga file in one
fread() pass worked the best. My conclusion would be
that (as someone mentioned earlier) fgetc() is implmented
poorly on Linux.
Tara Milana - WP Entertainmenthttp://wolfpack.twu.net/Comp graphics artist and programmer.
Advertisement
One solution would be to preload all the file with one fread into a cache buffer then consider this cache as a memory file where your image implementation can access required data through functions like memFread, memFgetc, memFseek, memFtell etc....
This way your minimize fread/fgetc implementation on any platform while speed up your access through memory.
hope this will help

This topic is closed to new replies.

Advertisement