45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 电脑教程 > 阅读资讯:如何使用Windows时钟函数?

如何使用Windows时钟函数?

2016-08-26 20:01:29 来源:www.45fan.com 【

如何使用Windows时钟函数?

Windows有个多媒体时钟函数:

timeGetTime

The timeGetTime function retrieves the system time, in milliseconds. The system time is the time elapsed since Windows was started.

DWORD timeGetTime(VOID);

单位为毫秒,精度比较高,使用时需要包含 "mmsystem.h"文件,并在工程中加入"winmm.lib" 文件。

另外Windows还提供了QueryPerformanceCounter函数可以取得高精度的当前的时钟周期数,因此可以用此函数写出比timeGetTime精度更高的记时器函数。

// 取得CPU每秒时间内的时钟周期数

__inline LONGLONG GetSecondCount()

{

static LARGE_INTEGER liCounter = {0};

if (0 == liCounter.QuadPart)

QueryPerformanceFrequency(&liCounter);

return liCounter.QuadPart;

}

// 返回当前时间 单位:毫秒

__inline DWORD highGetTime()

{

LARGE_INTEGER liCurrent = {0};

QueryPerformanceCounter(&liCurrent);

return (DWORD)(liCurrent.QuadPart * 1000 / GetSecondCount());

}

为了测试各时钟函数的精度究竟如何,笔者写了如下测试程序:

GetTickCount()

#include "conio.h"

#include "windows.h"

void main()

{

Sleep(1000);

DWORD old_time = GetTickCount();

for (int i = 0; i < 10; ++i)

{

int n = 0;

for (int j = 0; j < 500000; ++j)

{

if (j % 10 == 0)

n--;

else

n++;

}

DWORD time = GetTickCount();

DWORD dt = time - old_time;

old_time = time;

printf("n = %d 耗时:%d/n", n, dt);

}

_getch();

}

输出结果:

n = 400000 耗时:0

n = 400000 耗时:16

n = 400000 耗时:0

n = 400000 耗时:15

n = 400000 耗时:16

n = 400000 耗时:0

n = 400000 耗时:16

n = 400000 耗时:0

n = 400000 耗时:15

n = 400000 耗时:16

timeGetTime ()

#include "conio.h"

#include "windows.h"

#include "mmsystem.h"

#pragma comment(lib, "winmm.lib")

void main()

{

Sleep(1000);

DWORD old_time = timeGetTime();

for (int i = 0; i < 10; ++i)

{

int n = 0;

for (int j = 0; j < 500000; ++j)

{

if (j % 10 == 0)

n--;

else

n++;

}

DWORD time = timeGetTime();

DWORD dt = time - old_time;

old_time = time;

printf("n = %d 耗时:%d/n", n, dt);

}

_getch();

}

输出结果:

n = 400000 耗时:0

n = 400000 耗时:15

n = 400000 耗时:16

n = 400000 耗时:15

n = 400000 耗时:16

n = 400000 耗时:16

n = 400000 耗时:15

n = 400000 耗时:0

n = 400000 耗时:16

n = 400000 耗时:16

highGetTime ()

#include "conio.h"

#include "windows.h"

__inline LONGLONG GetSecondCount()

{

static LARGE_INTEGER liCounter = {0};

if (0 == liCounter.QuadPart)

QueryPerformanceFrequency(&liCounter);

return liCounter.QuadPart;

}

// 返回当前时间 单位:毫秒

__inline DWORD highGetTime()

{

LARGE_INTEGER liCurrent = {0};

QueryPerformanceCounter(&liCurrent);

return (DWORD)(liCurrent.QuadPart * 1000 / GetSecondCount());

}

void main()

{

Sleep(1000);

DWORD old_time = highGetTime();

for (int i = 0; i < 10; ++i)

{

int n = 0;

for (int j = 0; j < 500000; ++j)

{

if (j % 10 == 0)

n--;

else


本文地址:http://www.45fan.com/dnjc/68046.html
Tags: windows 函数 时钟
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部