C++ 28 Jan 2011 16:21:01

C++ Read Whole File Performance

A performance comparison of the speed of various ways to read an entire file into an std::string in C++.

Idea from BD-Calvin in #C++ on QuakeNet.

Sources

Things Tested

  • writing to a stringstream, then pulling data out as string
  • constructing a string via streambuf_iterator
  • getting file size via seeking, then preallocating a string to read into
  • getting file size via stat(), then ditto…

Observations

  • During the test, the seek method was twice as slow as the stat() method, until the file was buffered by the OS. For smaller files this would make no difference, but if one plans on reading larger files then stat() is better.

Linux: GNU g++ 4.4.1

  • Compiler: GNU g++ 4.4.1 -O3
  • Arch: Linux 2.6.27 x86_64, 2.66GHz Xeon, 8 GiB RAM
g++ 4.4.1TicksFactorAllocationsBytes Allocated
Stat4387025441.005104870440
Seek4398985201.005104870440
Stringstream10631133922.4223373300883
Iterator20891067524.7624268439653

Linux: LLVM clang++

clang++ 2.9 (trunk 124366)TicksFactorAllocationsBytes Allocated
Stat4384710721.005104870440
Seek4385152481.005104870440
Stringstream10686287282.4323373300883
Iterator25982866085.9324268439653

Windows: MSVC++ 2010

  • Compiler: MSVC++ 2010 _SECURE_SCL=0
  • Arch: Windows 7 64 bit, 1.60GHz Core i7 Q720, 8 GiB RAM
VC++ 2010TicksFactor
Stat4187792601.00
Seek4185559871.00
Stringstream482852691811.53
Iterator484514402511.57

Subscribe to the comments through RSS Feed

Leave a Reply

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image