C++ 测试程序运行时间

思路:使用time()函数测试时间差,头文件为:#include <ctime>

演示代码:

#include <iostream>

#include <ctime>

using namespace std;



// 顺序搜索

int seqSearch(int a[], const int len, const int x) {

    int i;

    

    for(i = 0; i < len; i++)

        if(a[i] == x)

            break;

    if(i == len)

        return -1;

    return i; // 否则返回i

}



int main(int argc, const char * argv[]) {

    int a[1001], x;

    long start, stop;

    

    for(int i = 0; i <= 1000; i++) // 初始化数组a

        a[i] = i + 1;

    cin >> x; // 要查找的数

    time(&start); // 开始计时

    int k = seqSearch(a, 1001, x);

    time(&stop); // 停止计时

    long runTime = stop - start; // 计算运行时间

    if(k == -1)

        cout << "查找失败!" << "查找时间为:" << runTime << endl;

    else

        cout << "查找成功,在数组中的下标为:" << k << "查找时间为:" << runTime << endl;

    return 0;

}

 


版权声明:本文为chuanzhouxiao原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。