Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function calling performance

Tags:

c++

c

I have called snprintf a few times consecutively with different arguments. I take the time needed for each snprintf. I found that the first call to snprintf takes the longest time. After that, the time needed to call the same function decreases until it converges. What is the reason for that? I have tried with other functions and also exhibit the same behavior.

I am asking this because it relates to testing the code performance. Normally in the main program it would be only be called periodically. However, when I test the function separately like in a loop, it would be faster, hence, resulting in inaccuracy of the measurement of performance.

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

snprintf(buffer, 32, "%d", randomGeneratedNumber1);
snprintf(buffer, 32, "%d", randomGeneratedNumber2);
   .
   .
   .
like image 878
Steveng Avatar asked Dec 06 '25 07:12

Steveng


2 Answers

The most likely explanation is that both the function code will end up in the instruction cache after the second time around just like the input data (if there is any) will be in the data cache. Furthermore, some branches may be predicted correctly the second time around.

So, all in all, "things have been cached".

like image 153
EboMike Avatar answered Dec 07 '25 20:12

EboMike


Your program may be dynamically linked to the library containing snprintf(). The first time delay would then be what is needed to load the library.

like image 27
mouviciel Avatar answered Dec 07 '25 20:12

mouviciel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!