简体   繁体   English

在if语句中测量时间c ++

[英]Measuring time in an if statement c++

Well... since 2 days ago I have been working on a project which records the clicks you make and repeats that over and over(just like a bot), the problem is at the moment that is recording the time between clicks because when measuring time with the " steady_clock::now " on a if statement, it is only declared in the if statement and if I try to make it a global variable with a NULL value, the compiler throws me an error because the " auto " variable type has to have a default value. 嗯...自2天前以来,我一直在从事一个项目,该项目会记录您做出的点击并一遍又一遍地重复(就像机器人一样),问题是此刻正在记录点击之间的时间,因为测量时如果在if语句上使用“ steady_clock :: now ”时间,则仅在if语句中声明它,并且如果我尝试使其成为具有NULL值的全局变量,则编译器会向我抛出错误,因为“ auto ”变量类型必须具有默认值。

#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
    }

}

I will really appreciate if someone responds my question. 如果有人回答我的问题,我将不胜感激。

Sorry for my english... 对不起我的英语不好...

This is where decltype is useful: 这是decltype有用的地方:

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

It is the type of the expression inside the parenthesis. 它是括号内表达式的类型。

First of all, you are trying to set up "start" twice and are also trying to use auto in an incorrect manner. 首先,您尝试设置两次“启动”,并且还尝试以错误的方式使用auto。 What is the compiler supposed to assume when it sees auto start = NULL ? 看到自动启动= NULL时,编译器应该假设什么? So kindly look up how it used. 因此,请仔细查看其用法。

Meanwhile,I think what you are looking for is something like this : 同时,我认为您正在寻找的是这样的:

#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; 
    }
}

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

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