4 ms·
You know what's even faster... write() I was writing part of a codebase where I couldn't use the heap, so all standard libraries were not on the cards, and I
by londons_explore 6y ago
You know what's even faster... write()
I was writing part of a codebase where I couldn't use the heap, so all standard libraries were not on the cards, and I ended up just using write(2, "hello\n", 6) to send the data direct to the kernel, and found the experience remarkably simple and unpainful.
- smabie 6y agoNo it's not, write is wayyyy slower. I just did a test, I write "hello\n" to a file 10,000,000 times. Using fprintf() and stdio.h, it takes 0.04s on my machine. Using write(), it takes 7.6s, over 2 orders of magnitude slower. Syscalls are extremely expensive and dominant the execution time unless you are writing large chunks of data all at once. Which is precisely why stdio.h exists, because it only occasionally flushes the buffer with write(). This can be observed when you get a segfault, often it seems like your print statements did not execute. One can use fflush() to force stdio.h to flush the buffer. write() on the otherhand, always writes the data, well, at least to the file buffer cache. fsync() is required to ensure that the data is on disk, though I've seen systems lie about that too.
- ilammy 6y agoIt depends on what you want to do. If that's sending data into the kernel right now – like procfs or a socket – then write() is what you need. fprintf() will provide more throughput by buffering the data and sending a batched write() later, but sometimes you need to send stuff right now and be sure that it's in the kernel when you get control back.
- MaxBarraclough 6y agoI imagine your compiler optimises the fprintf call into a call to fputs or puts.
- smabie 6y agofwrite, but yeah.
- scott00 6y ago> fsync() is required to ensure that the data is on disk, though I've seen systems lie about that too. Virtually all SSDs lie about this to a certain extent. They'll indicate a write is complete when it's in their cache. The cache is RAM; as long as the power stays on, the write will appear to have succeeded to readers, but if the power goes goes off before the drive flushes the cache, the write will disappear. The exception is high end enterprise drives, which come with a capacitor that stores enough power to flush the cache to persistent storage in the event of power loss.
- deleted 6y ago[deleted]