Test function running time


Test function running time

Time is money, efficiency is life! The quality of the program depends to a certain extent on its execution efficiency.

This is a method I found on the Internet to test the execution time of a function through a function. This should be relatively primitive. Maybe the compiler has this function. But it is good to understand some things in depth. I think this is also the direction I want to work hard on.

demo

clock():捕捉从程序开始运行到clock()被调用时所耗费的时间。这个时间单位是clock tick,即“时钟打点”。
常数CLK_TCK:机器时钟每秒所走的时钟打点数。

program

#include <iostream>
#include <time.h>

using namespace std;

clock_t start, stop;//clock_t是clock()函数返回的变量类型
double duration;//记录函数运行时间,以秒为单位

void PrintN(int N) {
    
    
	//不在测试范围内的准备工作写在clock()调用之前
	void PrintN(int N) {
    
    
	if (N) {
    
    
		PrintN(N - 1);
		cout << N << endl;
	}
	return;
}

int main() {
    
    
	int N;
	cin >> N;

	start = clock();
	PrintN(N);
	stop = clock();
	duration = ((double)(stop - start)) / CLK_TCK;
	cout << duration << endl;

	/*其他不在测试范围的处理写在后面,例如输出duration*/
	return 0;
}

This is a recursive program. After testing, the recursive program is slightly slower than the normal loop, and when N is greater than or equal to 100000, the recursive program crashes and the stack overflows.

Therefore, although recursion has its advantages, you must be careful when choosing recursion.

Welcome to personal blog: suzhigao66.top

Guess you like

Origin blog.csdn.net/weixin_44093867/article/details/104165778