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?
3 Answers
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.
-
2Also, consider being very careful of profile results that you run more than one time. You will have cached every file you touched, so the second run will more or less falsely appear much faster on the same set of files when you rerun. Jun 17, 2013 at 14:31
-
3Sort of like open heart surgery following a heart attack...yes it is expensive, but what's the alternative...?– JonathanJun 18, 2013 at 20:34
-
1And the surgery team is an incredibly talented team of C programmers from around the world? Jun 18, 2013 at 20:35
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.
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.
-
4How else do you propose doing what ls does? Avoiding stat makes no sense. If you did an ls on the directory any time in the past the files are probably already cached. Anyway - so how else do you get mtime? Other than calling stat or using ls which calls stat. Jun 17, 2013 at 14:43
expensive()
? Is that another system call?