我编写了两个功能相同的函数,但是使用了不同的算法。我使用time.h中的clock()比较执行时间,但结果不一致。
我试图更改函数的执行顺序,但似乎第一个要执行的函数将始终具有更长的运行时间
#include <stdio.h>
#include <time.h>
long exponent(int a, int b);
long exponentFast(int a, int b);
int main(void)
{
int base;
int power;
clock_t begin;
clock_t end;
double time_spent;
base = 2;
power = 25;
begin = clock();
long result1 = exponentFast(base, power);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Result1: %li, Time: %.9f\n", result1, time_spent);
begin = clock();
long result2 = exponent(base, power);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Result2: %li, Time: …Run Code Online (Sandbox Code Playgroud) c ×1