常见算法时间函数的增长趋势分析

《数据结构教程》(第5版)上机实验题1--实验题2:

目的:

理解常见算法时间函数的增长趋势

对以下函数用c++程序运行观察其变化:

            << "log2(n):
            << "      √n:
            << "      n:
            << "      n*log2(n):
            << "      n*n:
            << "      n^3:
            << "      2^n:
            << "      n!:       

1、从值的变化角度分析:

s-code:

#include<iostream>
#include<cmath>
using namespace std;
double factorial(double n)
{
    double result = 1;
    while(n)
    {
        result *= n--;
    }
    return result;
}
int main()
{
    int n = 1, i;
    cin >> i;
    while(i >= n)
    {
        cout << "log2(n):" << log2(n)
            << "      √n:" << sqrt(n) 
            << "      n:" << n 
            << "      n*log2(n):" << n*log2(n)
            << "      n*n:" << n*n 
            << "      n^3:" << n*n*n
            << "      2^n:" << exp2(n)
            << "      n!:" << factorial(n) << endl;
        n++;
    }
    return 0;
}

result of test:

2、从消耗的时间的角度分析:

介绍一个计时函数

#include<ctime>

clock_t start, end;
start = clock();
>>>//测试部分
end = clock();
cout <<(end - start)*1.0/CLOCKS_PER_SEC;  //单位是秒

s-code:

#include<iostream>
#include<cmath>
#include<ctime>
#include<string>
using namespace std;
double factorial(double n)        //求阶乘
{
    double result = 1;
    while(n)
    {
        result *= n--;
    }
    return result;
}
double testTime(double n)        //测试从0~n的消耗的时间
{
    clock_t start, end;
    start = clock();
    for(double i = 0; i <= n;i++);
    end = clock();
    return (end - start)*1.0/CLOCKS_PER_SEC;
}
void tPrint(string str, double n)    //output
{
    cout << "Start test " << str << ":" << endl;
    cout << "...
" << "End,time is :" << testTime(n) << "s
---------------------
";
}
int main()
{
    double n;
    cin >> n;
    tPrint("log2(n)",log2(n));
    tPrint("√n",sqrt(n));
    tPrint("n",n);
    tPrint("n^2",n*n);
    tPrint("n^3",n*n*n);
    tPrint("2^n",exp2(2));
    tPrint("n!",factorial(n));
    return 0;
}

result:

这里测试了
10
11
12
13
5000
五组数据显然当n越大时所消耗的时间的变化率差距就越大

 

注意:

这里的测试数据可能会由机器的性能不同产生差距,这时候就是检验机器性能的时候到了哈哈哈哈哈哈。。。。。

其实分析函数的变化用极限就一目了然了,用程序就是为了感受下等待的痛苦,哈哈。。。。。。

原文地址:https://www.cnblogs.com/sunrisepeak/p/9748586.html