二进制搜索是否真的在0时钟CPU时间内执行?

时间:2015-03-10 05:57:59

标签: c++ runtime clock binary-search

我编写了这个程序,它将从文件中读取一些数字,插入数组,执行线性搜索,对它们进行排序,以及执行二进制搜索(排序后)。

我使用时钟函数来测量执行上述每项任务所需的时间。

文件很大,有大约500万个数字。 插入需要时间并由时钟显示。 (从文件读取不是以最佳方式完成),线性搜索和排序也是如此。 但是,二进制搜索需要0秒才能执行。显然这是不对的。

我很好奇为什么它以毫秒为单位显示零时钟和时钟滴答数?

我在Windows 8.1,华硕,英特尔i-5,8GB内存,2.4 GHz处理器上运行。

这是输出:

$ make
g++  -c -Wall -g  search.cpp
g++  -o search search.o

$ ./search <input-5m.in
Time to insert: 26171
Time to Linear Search: 16
Yes!
Time to Sort: 1390
Time to Binary Search in milliseconds: 0
Time to Binary Search in clock ticks: 0
Time to Binary Search printed with "printf()": 0.000000
Yes!

这是代码。

using namespace std;
#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdio>
#include <iomanip>      // std::setprecision


clock_t clock(void);
...
...
...

int main(int argc, char** argv)
{
...
...
...

   clock_t startLinear, finishLinear;
   double elapsedTimeLinear =0;

    startLinear = clock();
    bool foundLinear = linearSearch(elements, n , x);
    finishLinear = clock();

    elapsedTimeLinear = (double)(finishLinear - startLinear)/CLOCKS_PER_SEC*1000;
    cout << "Time to Linear Search: " << elapsedTimeLinear << endl;
    foundLinear ? std::cout<<"Yes!"<<std::endl : std::cout<<"No!"<<std::endl;

    clock_t startSort, finishSort;
    double elapsedTimeSort =0;

    startSort = clock();
    sort(elements, elements+n);
    finishSort = clock();

    elapsedTimeSort = (double)(finishSort - startSort)/CLOCKS_PER_SEC*1000;
    cout << "Time to Sort: " << elapsedTimeSort << endl;

    clock_t startBinary, finishBinary;
    double elapsedTimeBinary =0, elapsedTimeBinaryTicks=0;

    startBinary = clock();
    //bool foundBinary = binarySearch(elements, n , x);
    bool foundBinary = binary_search(elements, elements+n, x);
    finishBinary = clock();

    elapsedTimeBinary = (double)(finishBinary - startBinary)/CLOCKS_PER_SEC*1000;
    elapsedTimeBinaryTicks = (double)(finishBinary - startBinary);
    cout << "Time to Binary Search in milliseconds: " << elapsedTimeBinary << endl;
    cout << "Time to Binary Search in clock ticks: " << elapsedTimeBinaryTicks << endl;
    printf("Time to Binary Search printed with \"printf()\": %f\n", elapsedTimeBinary);
    foundBinary ? std::cout<<"Yes!"<<std::endl : std::cout<<"No!"<<std::endl;

1 个答案:

答案 0 :(得分:4)

百万项目最多意味着20项比较。通常有效的代码(我没有看过你的代码)远低于1毫秒。在循环中执行要多次测量的事物,以便超过时钟分辨率。