Call function call

I called snprintfseveral times in a row with different arguments. I take the time needed for everyone snprintf. I found that the first call snprintftakes the longest time. After that, the time required to call the same function is reduced until it converges. What is the reason for this? I tried other functions and showed the same behavior.

I ask about this because it has to do with code performance testing. Usually in the main program this could be called only periodically. However, when I test the function separately, as in a loop, it will be faster, therefore, it will lead to inaccurate performance measurements.

The first call takes 4000 ++ ns, the second call takes 1700 ns, the third call takes 800 ns, until there are about 10 ++ calls, it is reduced to 130 ns.

snprintf(buffer, 32, "%d", randomGeneratedNumber1);
snprintf(buffer, 32, "%d", randomGeneratedNumber2);
   .
   .
   .
+3
source share
3 answers

The most likely explanation is that the function code will also be completed in the instruction cache after the second time, just as the input data (if any) will be in the data cache. In addition, some branches can be correctly predicted a second time.

So, overall, "things were cached."

+3
source

Your program may be dynamically linked to the library containing snprintf(). Then the first delay will be necessary to load the library.

+2
source

Search for TLB and cache. But for a small answer in these small codes, cache affects runtime. For large codes, in addition to the cache, many memory pages will be replaced and for later use will be replaced from the hard drive to your plunger. Therefore, when you often use part of the code, it will not be replaced, and thus, its execution time will be increased.

+1
source

Source: https://habr.com/ru/post/1769495/


All Articles