Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::ofstream and system touch

Tags:

c++

linux

Profiling one of my C++ programs I just discovered that calling std::ofstream(), when creating a bunch of files, takes much less time than using the system "touch".

So now I was wondering what OS function the std::ofstream is mapped to, on Linux.

Do you know what std::ofstream() calls to create a file?

Thanks

like image 965
rmbianchi Avatar asked Mar 05 '12 15:03

rmbianchi


3 Answers

If you are doing system("touch filename"); this is misleading and slow (and a security risk, and, and ...). It doesn't call the system as such, but spawns a shell, then runs the program (touch in this case) in it. Opening a stream will use some kind of actual system call that can directly access the filesystem. Possibly http://linux.die.net/man/2/open on Linux. Try running strace touch in a terminal to find out what system calls it is making. You could probably do the same with a simple c++ program you create just opening a file. Or if you are using an open source implementation (gcc) you can check the source.

like image 163
BoBTFish Avatar answered Oct 14 '22 03:10

BoBTFish


You should also consider the execution overhead of touch as a binary. I believe the performance increase is mostly due to having a persistent binary in the memory when measuring ofstream.

like image 32
perreal Avatar answered Oct 14 '22 03:10

perreal


Think about system(). It is going to fork/exec a shell which is going to load the touch binary, shared libs, etc., from disk, execute it, clean up the process and return.

If you are just using touch to create non-existing files then it mostly it is equivalent to std::ofstream.open() which is going to execute some function calls and ultimately resolve to the system call open() and eventually close(). A lot faster. However, if you are really emulating the capabilities of touch then it is more complicated. E.G. if the file already exists it will only change the timestamps, etc., and more is involved.

Regardless of your actual usage coding it in C++ is going to be faster than running an external program via system().

like image 1
Duck Avatar answered Oct 14 '22 03:10

Duck