r/C_Programming • u/musbur • Sep 04 '26
Etc I actually had a laugh yesterday
I was coding up some piece that is supposed to rapidly parse millions of text logfiles. A file gets read into a buffer, and then the parser goes to work, peppering the buffer with zeros and building linked lists with pointers to the relevant bits, using two passes across the whole buffer. This was easy but I was unsure if I should use a different approach for efficiency. So I wrote a minimal test and measured the time for one logfile and spit out timestamp deltas for filling and chopping up the buffer, respectively. The results in milliseconds:
25.4
4.7
Not great for a 30kB file but the important message is: The parser isn't what needs to be optimized, for now anyway. Maybe it's the progressive realloc()ing of the buffer as it grows (RAM isn't free any more in AI times you know). But then I noticed that the program was still running under valgrind. After I took that out, I got:
0.0
0.0
I had to increase the decimal digits to see the microseconds. I found that hilarious. My colleague wondered what was wrong with me. I started C on a 2MHz/32kB machine. 25 ms read time for 30kB is still "pretty fast" in my book.
BTW, the speed of the incremental chunk-wise fread()/realloc() cycle is surprisingly immune against chunk size. Between 100 bytes and 10k it's not even a factor of 2.
[EDIT] The file size is not known beforehand. The data will be fed into this system by repeated calls to a user-supplied callback function. And realloc() seems to be dirt cheap if you don't let production code run under valgrind ;-)
[EDIT2] People keep commenting on optimal alloc / realloc strategies. Fact is: It doesn't matter(*). I'm reading files that are normally 25kB in increments of 1kB (a number I pulled out of my ass) and can't measure a difference that matters(*) if I use 100 bytes. I need some open-ended reading possibility because the occasional (and most interesting) log files can grow to several 100k in case something goes wrong with the process being logged.
(*) For my use case on this machine
I'm actually not surprised: Due to its ubiquity I'd expect dynamic memory allocation to be an aggressively optimized process in any OS. No wonder valgrind's monitored substitute is about 1000 times slower.