Reputation: 403
Is the stat()
system call really expensive? I read somewhere that it is a costly system call to use. Is it, really? If so are there any other alternatives?
Upvotes: 17
Views: 7317
Reputation: 686
You can always use strace
to your executable. There is no need to recompile. This function allows you to get the actual execution time for each system call.
Upvotes: 7
Reputation: 117
The question arises as "Expensive v/s Required".
Every process on Unix runs in two modes : "User space" and "Kernel space", and when system calls like open(), write(), stat() are issued ,the process transits from User Space to the Kernel Mode which is expensive but only if we are not doing anything meaningful with this system call.Like if you are using stat() to only print the last accessed time of the file and nothing more we are doing,then probably it should me avoided.
So firstly, there should be a good reason to call stat(). Secondly if you want to compare the relative execution times of different pieces of your code,use any profiling tool ,which will provide you the exact statistics to prove which function call is expensive and which is not.
Upvotes: 2
Reputation: 8184
In a typical setting, stat(2)
, fstat(2)
, and lstat(2)
are the only sane techniques for getting file information. If you're seeing performance problems, it would be worthwhile to profile your application and see what happens.
To profile, compile with gcc -pg
and run the executable with gprof(1)
.
You could, potentially, switch to using a larger library like Qt, but that will not likely handle any performance problems, and they will likely use stat(2)
anyway.
So, whether it's expensive or not, there are no reasonable alternatives.
That said, as in Jim Mcnamara's comment, it's not expensive for precisely these reasons. As there's no other alternative, the glibc and linux programmers have made it as performant as possible.
Upvotes: 19