如果使用的是控制台运行程序,会显示运行时间,不过有的比如我用的VS CODE 不会显示运行时间,影响对时间复杂度的判断
显示运行时间代码如下
#include <iostream>
#include <cmath>
#include <time.h>
using namespace std;
/**
* 普通的求幂函数
* @param base 底数
* @param power 指数
* @return 求幂结果的最后3位数表示的整数
*/
long long normalPower(long long base, long long power) {
long long result = 1;
for (int i = 1; i <= power; i++) {
result = result * base;
result = result % 1000;
}
return result % 1000;
}
int main() {
clock_t start, finish;
//clock_t为CPU时钟计时单元数
long long base, power;
cin >> base >> power;
start = clock();
//clock()函数返回此时CPU时钟计时单元数
cout << normalPower(base, power) << endl;
finish = clock();
//clock()函数返回此时CPU时钟计时单元数
cout << "the time cost is " << double(finish - start) / CLOCKS_PER_SEC;
//finish与start的差值即为程序运行花费的CPU时钟单元数量,再除每秒CPU有多少个时钟单元,即为程序耗时
return 0;
}
运行结果是
2 100000000
376
the time cost is 1.348
本文介绍了一种在C++中测量程序运行时间的方法,通过使用clock()函数记录程序开始和结束时的CPU时钟计时单元数,计算出程序的运行时间。此方法适用于需要评估算法效率和时间复杂度的场景。
1246

被折叠的 条评论
为什么被折叠?



