Search code examples
cmacosfilefilesize

What is the fastest way to detect file size is not zero without knowing the file descriptor?


To explain shortly why I need this, I am currently doing the detection by stat(2). I don't have control over the file descriptor (may get used up by some other thread as my code is getting injected to replace syscalls) , so i can't use fstat(2) (which is faster). I need to do this check a lot of times, so is there a faster way to do the same thing? I am checking the same file in different processes which do not have a parent child relation.


Solution

  • You should probably benchmark it for yourself.

    I've measured

    //Real-time System-time
    272.58 ns(R)    170.11 ns(S)  //lseek
    366.44 ns(R)    366.28 ns(S)  //fstat
    812.77 ns(R)    711.69 ns(S)  //stat("/etc/profile",&sb)
    

    on my Linux laptop. It fluctuates a little between runs but lseek is usually a bunch of ns faster than fstat, but you also need a fd for it and opening is quite expensive at about 1.6µs, so stat is probably the best choice for your case.


    As tom-karzes has noted, stat should dependent on the number of directory components in the path. I tried it on a PATH_MAX long "/foo/foo/.../foo" directory and there I'm getting about 80µs.