dimanche 26 janvier 2020

Why are my runtime numbers wrong when trying to measure how long a function takes to return?

I have 30 vectors of sorted ints, the vectors range in size from 2^0 to 2^30. I am trying to measure how long binary search will take to find a value in each, but the reported time speeds up as the vectors get larger. The time doesn't actually take longer, the reporting is wrong.

Here's my code:

int main() {
    const unsigned int maxPower = 30;  // 2^maxPower
    long long n = 1 << maxPower;  // n = 2^i

    for (int i = 0;  i <= maxPower; ++i) {

        std::vector<long long> haystack = getVector(i);  // returns a sorted vector of size i
        long long needle = haystack.size()/2 + 1;

        clock_t t1 = clock();  // start timer
        binary_search(haystack, needle);
        clock_t t2 = clock();  // end timer

        clock_t dt = t2 - t1;
        double clocks_per_rep = ((double)dt)/n;
        double seconds = clocks_per_rep/CLOCKS_PER_SEC;

        std::cout << seconds << std::endl;
    }

    return 0;
}


>> 
1e-06
1e-06
0
1e-06
0
1e-06
0
0
0
1e-06
0
0
0
1e-06
0
0
0
1e-06
1e-06
2e-06
1e-06
1e-06
1e-06
1e-06
1e-06
1e-06
1e-06
0
1e-06
1e-06
1e-06

I've tried using high_resolution_clock as well but couldn't get that to even display anything but 0's.


EDIT: My original problem has been solved but now I have a new one: there's hardly any variation in my timings even when some take much longer than others. Here's my new code and output:

int main() {
    const unsigned int maxPower = 30;  // 2^maxPower
    long long n = 1 << maxPower;  // n = 2^i

    for (int i = 0;  i <= maxPower; ++i) {

        std::vector<long long> haystack = getVector(i);  // returns a sorted vector of size i
        long long needle = haystack.size()/2 + 1;

        clock_t t1 = clock();  // start timer
        ternary_search(haystack, needle);
        clock_t t2 = clock();  // end timer

        clock_t dt = t2 - t1;
        double seconds = (double)dt/CLOCKS_PER_SEC;

        std::cout << seconds << std::endl;
    }

    return 0;
}

>>
1e-06
1e-06
1e-06
0
1e-06
1e-06
0
0
1e-06
0
0
1e-06
0
0
0
0
1e-06
1e-06
1e-06
4e-06
3e-06
3e-06
1e-06
2e-06
3e-06
3e-06
3e-06
2e-06
3e-06
3e-06
3e-06

Aucun commentaire:

Enregistrer un commentaire