Why does a function has so different performance timing?

Viewed 108

I'm learning C++. While solving Leetcode 0009, I wanted to time the function. For 4 different inputs I got the following results consistently:

1
time: 8993
0
time: 88
0
time: 1374
1
time: 1199

My question is why is it taking so long for the first run but not the others? And any other feedback is appreciated.

Here is the code:

//leetcode 0009. Palindrome Number
#include <iostream>
#include <sstream>
#include <string>
#include <chrono>

bool isPalindrome(int x) {
    if (x < 0) return false;
    std::stringstream ss;
    ss << x;
    std::string str;
    ss >> str;

    int len = str.length();

    for (int i=0; i<len/2; i++) {
        if (str[i] != str[len-i-1])  {
            return false;
        }
    }
    return true;
}    

void timeit (bool (*f)(int), int x) {
    auto s = std::chrono::high_resolution_clock::now();
    auto res = f(x);
    auto e = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(e - s);
    std::cout << res << std::endl;
    std::cout << "time: " << duration.count() << std::endl; //true

}

int main() {
    timeit(isPalindrome, 121);
    timeit(isPalindrome, -121);
    timeit(isPalindrome, 10);
    timeit(isPalindrome, 1001);
}
0 Answers
Related