在IF语句C 中测量时间

Measuring time in an if statement c++

本文关键字:测量 时间 IF 语句      更新时间:2023-10-16

好吧...因为两天前,我一直在研究一个项目,该项目记录了您的点击,并一遍又一遍地重复(就像bot一样(,问题在于在点击之间记录时间的时刻,因为在使用if语句上测量" steady_clock :: Now "的时间时,仅在if语句中声明,如果我尝试使其成为全局变量使用零值,编译器会给我带来错误

#include<chrono>
using namespace std::chrono;
auto start = NULL; //this is an error
int main()
{
     if (!GetAsyncKeyState(VK_LBUTTON))
    {
        auto start = steady_clock::now();
    }
     else if (GetAsyncKeyState(VK_LBUTTON))
    {
        auto end = steady_clock::now();
        std::chrono::duration<double> elapsed = end - start;   //here the compiler throws me an error because start is not declared
    }
}

如果有人回答我的问题,我真的很感激。

对不起我的英语...

这是decltype有用的地方:

decltype(steady_clock::now()) start;
// ...
start = steady_clock::now();

是括号内表达式的类型。

首先,您正在尝试两次启动"启动",并且也试图以不正确的方式使用自动。当它看到自动启动= null 时,应该假设编译器应该假设?因此,请查找它的使用方式。

同时,我认为您要寻找的是这样的东西:

#include<chrono>
std::chrono::steady_clock::time_point start; // You can mention the type of start and end explicitly,.
std::chrono::steady_clock::time_point end;
int main()
{
    if (!GetAsyncKeyState(VK_LBUTTON))
    {
        start = std::chrono::steady_clock::now();
    }
    else // don't think you needed an else-if here.
    {
        end = std::chrono::steady_clock::now();
        std::chrono::duration<double> elapsed = end - start; 
    }
}