如何写一个简单的c语言程序测试电脑的性能?
这里使用一种神奇的数列:斐波那契数列,写一段简单的递归函数,通过电脑跑完函数所需要的时间进行计算,代码如下
#define _CRT_SECURE_NO_WARNINGS 1;
#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
int fib(int n, int* count) //斐波那契数列的递归实现
{
if (n == 1 || n == 2)
return 1;
else
{
(*count)++; //计算的次数
return fib(n - 1, count) + fib(n - 2, count); //这里的count是指针变量,不需要&,和main函数中的不一样,main函数中的count是整型变量
}
}
int main()
{
int n = 0;
int ret = 0;
printf("请输入\n");
do //多次输入
{
int count = 0;
scanf("%d", &n);
if (n)
{
double start = GetTickCount(); //Windows提供的函数,获取电脑开机到现在的时间,单位是毫秒
ret = fib(n, &count);
double end = GetTickCount(); //通过两段时间相减,确定电脑计算用的时间
printf("fib(%d) = %d 用时 = %.1lf秒 计算次数 = %d 次\n", n, ret, (end - start) / 1000, count);
}
} while (n); //遇到0跳出循环
system("pause");
return 0;
}
以上是我的笔记本电脑跑下来的情况,台式机的话我没有数据,我的笔记本电脑属于中规中矩的配置,经过测试,fib(41)在4秒以内,fib(42)在6.5秒以内,fib(43)在10秒以内,在笔记本电脑中属于很强的配置了。
感谢阅读,快去测试下你的电脑。