如何获取子函数运行时间

往往在解决一些问题时会有很多种算法去实现它,那么在多种

方法一:运行time()函数

time()返回的是单位为秒的时间,因此不适用于完成小型代码的测试。
测试函数的算法流程图如下:
辗转相除法

(1)源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "stdio.h"
#include "time.h" //需要包含头文件
int gcd(int a,int b)
{

if(a%b==0)
return b;
else
return gcd(b,a%b);
}

int main()
{
int t;
time_t start;
time_t end;
time(&start);
t=gcd(45,30);
time(&end);
printf("秒数为:%ld\n", end-start);
}

(2)运行结果
time函数运行结果

方法二:运用GetTickCount()函数

GetTickCount()函数是以毫秒为单位的时间。返回值为DWORD,属于windows程序设计。
测试函数的算法流程图如下:
穷举法
(1)源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "iostream"
#include "windows.h"//需要包含头文件windows.h

using namespace std;

int divisor(int a,int b)
{
int temp;
temp = (a>b)?b:a;
while(temp>0)
{
if(a%temp==0&&b%temp==0)
break;
temp--;
}
return(temp);
};

int main()
{
DWORD start_time = GetTickCount();
int a,b,t1;
t1 = divisor(789,47);
DWORD end_time = GetTickCount();
cout<<"The time is:"<<(end_time-start_time)<<"ms"<<endl;
}

(2)运行结果:
GetTickCount函数

方法三:运用QueryPerformanceCounter()函数

QueryPerformanceCounter()函数返回的是以微妙为单位的时间。精度在98下可能是35微妙,2000下可以达到1微妙左右
测试函数的算法流程图如下:
更相减损法
(1)源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include<Windows.h>
#include <math.h>

using namespace std;

template<typename func>
int performance_test(func f){ //通过传入成员函数指针,进行调用,测试函数运行时间
LARGE_INTEGER frec, start, end; //WindowsAPI测试程序运行时间
QueryPerformanceFrequency(&frec);
QueryPerformanceCounter(&start);
QueryPerformanceCounter(&end);
return (end.QuadPart - start.QuadPart) * 1000000000 / frec.QuadPart;
}
//更相减损法
int test(int m,int n) {
int i=0,temp,x;
while(m%2==0&&n%2==0)
{
m/=2;
n/=2;
i+=1;
}

//m保存大的值
if(m<n)
{
temp=m;
m=n;
n=temp;
}

while(x)
{
x=m-n;
m=(n>x)?n:x;
n=(n<x)?n:x;
if(n==(m-n))
break;
}

if(i==0)
return n;
else
return(int)pow(2,i)*n;
}

int main(){
int t;
t=test(478,98);
cout << "The time is:"<<performance_test(test) <<"微秒"<< endl; //传入函数对象,返回的是一个微秒的运行时间
}

(2)运行结果:
QueryPerformanceCounter()函数