用于计时测试的函数

用于计时测试的函数

测试软件VC++6.0和VS2019,测试平台windows

GetTickCount函数:
#include<stdio.h>
#include <windows.h>

void MyFunction()
{
    for (int i = 0; i < 189; i++)
        printf("Hello!\n");
}

void test()
{
    DWORD t1, t2;
    t1 = GetTickCount();
    MyFunction();//调用函数
    t2 = GetTickCount();
    printf("Use Time:%f\n", (t2 - t1) * 1.0 / 1000);//以ms为单位,转换单位为s
}

int main()
{
    test();
    return 0;
}

注意事项

需引入windows.h头文件,可以存储的最大值是2^32 ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0。

特别注意:这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度为18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行。

* 连续触发200次,实测下来,最小间隔在15ms。

clock函数:
#include<stdio.h>
#include<time.h>
void MyFunction()
{
	for(int i = 0;i<29;i++)
printf("Hello!\n");
}
clock_t start,stop;
/*clock_t是clock()函数返回的变量类型,即长整型,用了自定义类型*/
double duration;
/*记录被测函数运行时间,以秒为单位*/
void test()
{	
	/*不在测试范围内的准备工作写在clock()调用之前*/
	start = clock();/*开始计时*/
	MyFunction();/*被测函数*/
	stop = clock();/*停止计时*/
	duration = ((double)(stop - start))/CLK_TCK;/*其他不在测试范围的处理写在后面,例如输出duration的值*/
    /*CLK_TCK为常数,不同计算机值可能不同*/
	printf("%f",duration);
}
int main()
{
	test();
	return 0;
}

注意事项

需引入头文件time.h,最小单位是1ms。

猜你喜欢

转载自blog.csdn.net/Sun_Raiser/article/details/104300864