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
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.
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
.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With