gpt4 book ai didi

c - 我在 Windows 上用 C 语言做了高分辨率计时?这样对吗?

转载 作者:行者123 更新时间:2023-11-30 20:15:23 25 4
gpt4 key购买 nike

#include <windows.h>
#include <stdio.h>

TASK (Task2ms)
{
printf("Hello"):

SetEvent(Task1);
}

void main()
{
int arg;
HANDLE Task1;
HANDLE HTimer1 =NULL;
HANDLE HTimerQueue1 = NULL;
Task1 = CreateEvent(NULL, TRUE, FALSE, NULL);
if(NULL == Task1)
{
printf("CreateEvent failed (%d)\n", GetLastError());
return 1;
}

//create a timer queue
HTimerQueue1 = CreateTimerQueue();
if(NULL == HTimerQueue1)
{
printf("CreateTimerQueue failed (%d)\n", GetLastError());
return 2;
}

//phNewTimer - Pointer to a handle; this is an out value
//TimerQueue - Timer queue handle. For the default timer queue, NULL
//Callback - Pointer to the callback function
//Parameter - Value passed to the callback function
//DueTime - Time (milliseconds), before the timer is set to the signaled state for the first time
//Period - Timer period (milliseconds). If zero, timer is signaled only once
//Flags - One or more of the next values (table taken from MSDN):

//set the timer to call the timer routine in 2ms
if(!CreateTimerQueueTimer( &HTimer1, HTimerQueue1, (WAITORTIMERCALLBACK)TASK, &arg, 2,0,0))
{
printf("CreateTimerQueueTimer failed (%d)\n", GetLastError());
return 3;
}

//Do other work here

printf("Call timer routine in 2 milliseconds...\n");
// wait for the timeröqueue thread to complete using an event

if (WaitForSingleObject(Task1, INFINITE) !=WAIT_OBJECT_0)
printf("WaitForSingleObject failed (%d)\n", GetLastError());
CloseHandle(Task1);

//Delete all timers in the timer queue
if(!DeleteTimerQueue(HTimerQueue1))
printf("DeleteTimerQueue failed (%d)\n", GetLastError());

return 0;
}

我创建了一个名为 Task(task 2ms) 的函数,该函数每 2ms 调用一次。所以我为此创建了一个计时器队列。如果我这样做,那么任务函数将每 2 毫秒调用一次。这是正确的吗?

最佳答案

...每 2 毫秒调用一次。这是正确的吗?

不,这是不对的。

设置定时器队列定时器时,需要遵循文档:

您将DueTime指定为2毫秒!

DueTime:在计时器首次发出信号之前必须经过的相对于当前时间的时间量(以毫秒为单位)。

并且您将Period指定为零!

计时器的周期,以毫秒为单位。如果该参数为零,则定时器发出信号一次。如果该参数大于零,则计时器是周期性的。周期性计时器会在每次经过一段时间后自动重新激活,直到计时器被取消。

您还必须将Period指定为2毫秒。

但是您的代码无论如何都无法处理多个计时器事件。它只是在第一个计时器事件发生后结束。因此,无论如何,您可能需要在代码上花费更多时间,例如:

while (1) {
if (WaitForSingleObject(Task1, INFINITE) == WAIT_OBJECT_0) {
printf("2 ms event occurred!\n");
} else {
printf("WaitForSingleObject failed (%d)\n", GetLastError());
break;
}
}

P.S.:Task2ms有什么用?并且: printf("Hello"): 必须替换为 printf("Hello\n"); (使用分号作为终止符/语句分隔符!)。您实际上是在询问您从未尝试过编译的代码。您不应期望人们热衷于回答此类问题。

关于c - 我在 Windows 上用 C 语言做了高分辨率计时?这样对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19711773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com