This is a system call, like other answers, and other answers give you a good way to evaluate the value of your system. (Once it doesn’t have to work much in the kernel, so it’s pretty close to the cost of pure syscall builds. And Linux did everything it could to efficiently implement system calls. So, in this sense, you may find it pretty well optimized.)
Unlike the other answers, I would not find it so cheap that you don’t have to worry about it automatically. If it's in the inner loop, it depends on what else you do in your inner loop. If these are requests for server processing, it will probably cause a lot of system calls for each request, and another one will not really change the cost of each request. However, I saw code in which the syscall overhead from calling time () (or gettimeofday (), which it really comes down to) adversely affects.
If you are worried about cost, the next thing to ask yourself is that cheaper ways to find time are available. In general, it will not be cheaper. If you are on x86, you can request a CPU with the rdtsc instruction (and most likely it is an analog on other processor architectures) - this is one assembly instruction that does not have privileges, so you can paste it into your code anywhere. But there are many pitfalls - rdtsc does not always increase at a predictable speed, especially if the processor speed changes to manage power, depending on the particular processor model you are using; values may not be synchronized across multiple processors, etc. The OS tracks all of this and provides you with a friendly, easy-to-use version of the information when you call gettimeofday ().
metamatt
source share