I have this simple hello world program:
#include <stdio.h>
int main() {
printf("Hello, world!\n");
return 0;
}
I compiled this program with LLVM Clang (v15.0.1, built from Homebrew, so not Apple's version) like normal, then I ran and timed the outputs. To my surprise, the first time the program ran, it took nearly 10x longer than the second time, but the next three executions run much faster.
$ clang test.c -o test
$ time ./test
Hello, world!
real 0m0.169s
user 0m0.001s
sys 0m0.002s
$ time ./test
Hello, world!
real 0m0.017s
user 0m0.001s
sys 0m0.006s
$ time ./test
Hello, world!
real 0m0.004s
user 0m0.001s
sys 0m0.002s
$ time ./test
Hello, world!
real 0m0.008s
user 0m0.001s
sys 0m0.005s
I'm running this on an Intel Core i5 mac, running macOS Big Sur v11.6.8. The shell is the bash
shipped with macOS.
Nothing in my code deals with time, and I don't think there's anything to cache, so I'm not sure why the first execution runs so slow. I suspect that the OS might be doing some kind of optimization, but I don't know what/how. What is the cause of this large discrepancy in runtimes?
echo 3 | sudo tee /proc/sys/vm/drop_caches
before next run. – Purnelltime /bin/true
. – Rocamboletime ./test
does, so if "recent" load more than a second ago was relevant, the first run should be the fastest. (Unless it takes so much longer to typetime ./test
than to up-arrow it...) With a software governor, a process using up its timeslice will typically trigger a jump to max frequency, but that'll age away very soon. – Rocamboletime ./test; time ./test
on the same command line, or a shell loop, you could have an effect, but other effects are clearly more significant. – Rocambolesync && sudo purge
to eliminate disk caching? – Keep0.087
seconds, much slower than runs after it, but about twice as fast as the post-compile run. It looks like disk caching is part of it, but I think there's a bit more to it. – Equipmenttime ./helloworld
, the first run is takesreal 0m0.051s
and subsequent runsreal 0m0.006s
toreal 0m0.009s
. I'm on this question because I've noticed this too for a while. – Elflock