繁体   English   中英

time.h 时钟() 在Windows 下如何工作?

[英]How does time.h clock() work under Windows?

我正在尝试为 C 中的嵌入式系统创建一个简单的队列计划。这个想法是在循环中根据Tasks[]数组中声明的时间限制调用一些函数。

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

//Constants
#define SYS_TICK_INTERVAL   1000UL
#define INTERVAL_0MS        0
#define INTERVAL_10MS       (100000UL / SYS_TICK_INTERVAL)
#define INTERVAL_50MS       (500000UL / SYS_TICK_INTERVAL)

//Function calls
void task_1(clock_t tick);
void task_2(clock_t tick);
uint8_t get_NumberOfTasks(void);

//Define the schedule structure
typedef struct
{
    double Interval;
    double LastTick;
    void (*Function)(clock_t tick);
}TaskType;

//Creating the schedule itself
TaskType Tasks[] =
{
    {INTERVAL_10MS, 0, task_1},
    {INTERVAL_50MS, 0, task_2},
};

int main(void)
{
    //Get the number of tasks to be executed
    uint8_t task_number = get_NumberOfTasks();

    //Initializing the clocks
    for(int i = 0; i < task_number; i++)
    {
        clock_t myClock1 = clock();
        Tasks[i].LastTick = myClock1;
        printf("Task %d clock has been set to %f\n", i, myClock1);
    }

    //Round Robin
    while(1)
    {       
        //Go through all tasks in the schedule
        for(int i = 0; i < task_number; i++)
        {
            //Check if it is time to execute it
            if((Tasks[i].LastTick - clock()) > Tasks[i].Interval)
            {
                //Execute it
                clock_t myClock2 = clock();
                (*Tasks[i].Function)(myClock2);
                //Update the last tick
                Tasks[i].LastTick = myClock2;
            }
        }
        Sleep(SYS_TICK_INTERVAL);       
    }
}

void task_1(clock_t tick)
{
    printf("%f - Hello from task 1\n", tick);
}

void task_2(clock_t tick)
{
    printf("%f - Hello from task 2\n", tick);
}

uint8_t get_NumberOfTasks(void)
{
    return sizeof(Tasks) / sizeof(*Tasks);
}

代码编译时没有任何警告,但我想我不明白命令clock()如何工作的。

在这里你可以看到我运行程序时得到的结果:

F:\AVR Microcontroller>timer
Task 0 clock has been set to 0.000000
Task 1 clock has been set to 0.000000

我尝试将IntervalLastTick从 float 更改为 double 以确保这不是精度错误,但仍然不起作用。

%f不是打印myClock1的正确格式说明符,因为clock_t可能不是double 你不应该假设clock_tdouble 如果要将myClock1打印为浮点数,则必须手动将其转换为double

printf("Task %d clock has been set to %f\n", i, (double)myClock1);

或者,使用宏CLOCKS_PER_SECmyClock1转换为秒数:

printf("Task %d clock has been set to %f seconds\n", i,
    (double)myClock1 / CLOCKS_PER_SEC);

此外,您在调度程序循环中的减法是错误的。 想一想: clock()会随着时间变大,所以Tasks[i].LastTick - clock()总是产生一个负值。 我想你想要clock() - Tasks[i].LastTick代替。

clock功能的行为取决于操作系统。 在 Windows 上它基本上运行挂钟,而在例如 Linux 上它是进程 CPU 时间。

此外, clock本身的结果是无用的,它仅用于比较两个时钟(例如clock_end - clock_start )。

最后, clock_t类型( clock返回的)是整数类型,如果您将差异(如上面的那个)转换为例如double并除以CLOCKS_PER_SEC ,则只能获得浮点值。 尝试使用"%f"格式打印clock_t将导致未定义的行为

阅读clock参考可能会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM