c - Why does the first printf take longer? -


I was playing with high precision timers and one of my first tests was to use rdtsc to measure printf . Below is my test PGMGM after its output. The first thing I've seen is that the first time the printf runs, it takes 25 times more time on the first print, which is on the subsequent impressions. Why is it like this?

  #include & lt; Stdio.h & gt; # Include & lt; Stdint.h & gt; // Sample code obtained from Wikipedia __inline__ uint64_t rdtsc (zero) {uint32_t Lo, hi; __asm__ __volatile__ ("xorl %% eax, %% eax \ ncpuid" ::: "% rax", "% rbx", "% rcx", "% rdx"); __asm__ __volatile__ ("rdtsc": "= one" (lo), "= d" (hi)); Return (uint64_t) hi & lt; & Lt; 32 | Take; } Int main (int argc, const char * argv []) {unsigned int i; Uint64_t counter [10]; Uint64_t sum = 0; For (i = 0; i <-10; i ++) {counter [i] = rdtsc (); Printf ("hello, world \ n"); Counter [I] = RDSC () - Counter [I]; } (I = 0; i <-10; i ++) {printf ("counter [% d] =% lld \ n", i, counter [i]); Yoga + = counter [i]; } Printf ("avg =% lld \ n", zodiac / 10); Return 0; }   

and output:

  Hello, World Hello, World Hello, World Hello, World Hello, World Hello, World Hello, World Hello, Hello World , World Hello [0] = 108165 Counter [1] = 6375 Counter [2] = 4388 Counter [3] = 4388 Counter [4] = 4380 Counter [5] = 4545 Counter [6] = 4215 Counter [7] = 4290 Counter [8] = 4237 Counter [9] = 4320 avg = 14930   

(For reference, it was compiled with GCC on OSX)

My guess is that the first call on printf, stdout number Resources are not in the cache and will need to call in the cache it - so it all calls to slow after cash already hot.

The second possible explanation is that, if it is on Linux (I can not believe it is also applicable on OSX), the program needs to be set up Stream Orientation (ASCII vs Unicode) Using a call, a function is performed on the first call and the stream is stable until it is closed. I do not know what's on top of setting up this orientation, but it's a one-time cost.

Please feel free to correct me if someone thinks that I am completely wrong.

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -