How to measure the duration of a keypress hold C++ [closed] - c++

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed yesterday.
Improve this question
Hi I am creating a small program for a game analysis (its a hobby and I have no idea what I am doing so please don't expect much from me) in C++ which can do three things.
Recognise and count a pressed key (upon release increase times pressed by one)
Measure the sum of press duration of a certain key (already made a timer class for that purpose)
Output all in a .txt file like this:
Letters: A Times_pressed: 14 Duration: 10000ms
Here is my code so far I started with count the times but I cannot figure it out how it works. It increments very fast when 'A' key is pressed and when released it stops. Which is not what I really want. I want increment of only +1 even if I hold it for ages but upon release and repeat next increment of +1.
Any advice or help would be highly appreciated!
#include <iostream>
#include <windows.h>
int main()
{
int aKeyCount{0};
while (true)
{
if (GetAsyncKeyState('A') & 0x8000)
{
++aKeyCount;
std::cout << aKeyCount << std::endl;
}
}
return 0;
}

The reason why your code increments very fast when the 'A' key is pressed is because GetAsyncKeyState() returns a value of 1 as long as the key is held down. In other words, your code is counting every time through the loop that the key is held down, which is many times per second.
a boolean flag is added to keep track of whether the 'A' key was previously pressed or not.
#include <iostream>
#include <windows.h>
int main()
{
int aKeyCount{0};
bool wasKeyPressed{false};
while (true)
{
if (GetAsyncKeyState('A') & 0x8000)
{
if (!wasKeyPressed)
{
++aKeyCount;
std::cout << aKeyCount << std::endl;
}
wasKeyPressed = true;
}
else
{
wasKeyPressed = false;
}
}
return 0;
}

Related

How do i make a piezo play 3 times and then stopping in Arduino? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
EDIT: https://www.tinkercad.com/things/ampvgOj75D1
This is the link to my tinkercad project witch contains the wiring of the circuit, sorry that i forgot it's also needed to get the code working.
I need this code to make the piezo play 3 times and then stopping it completely, the while() loop does not work for some reason.
I tried moving around the i++ function but it does not work. If i state i=0; globally the piezo never plays, if i put it in loop() it keeps repeating without stopping the third time.
int i=0;
const byte speakerPin=9;
unsigned long CurrentMillis;
unsigned long lastPeriodStart;
const int onDuration=100;
const int periodDuration=500;
void setup()
{
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop()
{
CurrentMillis = millis();
Serial.println(i);
while(i<=3)
{
if (CurrentMillis-lastPeriodStart>=periodDuration)
{
lastPeriodStart = millis();
tone(speakerPin,550, onDuration);
}
i++;
}
}
Your actual code not work due to variable i is incremented in every loop. So this mean i is more then 3 in very short time and if statement is still false.
If you move i++ statement inside if, your code not leave while loop, because CurrentMillis is not updated.
My recomendation:
use Serial.println("message"); to trace your code, in all branches your code
move i++; statement inside if
replace while statement by if

Use of curly brackets in conditional statement causes slightly lower performance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Introduction
I am working on a coding practice question where people post their execution time to see who achieves the best performance. I wrote a recursive function for calculating the modular exponentiation of large (3 digits) numbers.
What is the problem?
I realized that when I don't use curly brackets I am getting a faster execution time. I kept testing this finding multiple times and I consistently got the same result.
Code 1
#include <iostream>
using namespace std;
int modExp(int a, int b, int c){
if(b==0)
return 1;
return (a*modExp(a,b-1,c))%c;
}
int main()
{
int A = 450;
int B = 768;
int C = 517;
int result = modExp(A,B,C);
cout << "Result is: " << result << endl;
return 0;
}
Execution time of code 1
Code 2
#include <iostream>
using namespace std;
int modExp(int a, int b, int c){
if(b==0){
return 1;
}
return (a*modExp(a,b-1,c))%c;
}
int main()
{
int A = 450;
int B = 768;
int C = 517;
int result = modExp(A,B,C);
cout << "Result is: " << result << endl;
return 0;
}
Execution time of code 2
What I think is going on:
Although once the execution times are expressed in 3 significant digits it appears that Code 1 is twice as much faster than Code 2, I think this is just a rounding issue. The execution time is probably something like 0.001465s without the curly brackets and when I use the curly brackets, it is causing enough delay to cause the execution time to be rounded up to 0.002s.
Is it possible to increase the significant digits of the execution time?
Am I right with my hypothesis? Why do you think the delay is caused?
You're seeing statistical noise from a single run of the executables. Both executables will be identical for this input (the compiler understands that they are logically equivalent and produce output accordingly), and if you run them thousands or millions of times and take an average, you'll see the same execution time.
It's true that sometimes subtle differences in syntax can have subtly different semantics, and thus end up performing differently, but use of optional scope braces is not one of those cases.

Do while loops stop verifying after condition isn't met anymore?

I have recently started learning c++ and I have a question regarding the last section I reached, the while loop one.
In this code:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
return 0;
}
will the while command continue checking if i <=5 after the value goes over 5 or will it stop?
If I was making a program and changed the value of i down the line to one that meets the condition of the loop would it start again or would I have to rewrite the loop code again?
Thanks in advance for the answers!
edit: Thanks for your answers and comments. I tried putting into code what I was thinking and I noticed that changing the value of i after the loop didn't make it start again(meaning that it had already stopped checking after i surpassed 5).
I realize it was a stupid question that I could have simply solved by trying to put it into code, but I still asked for answers just to be sure. Thanks again!
If you changed i to 0 after the loop has ended like this:
int main()
{
int i = 0;
while (i <= 5) {
cout << "Hello" << endl;
i = i + 1;
}
i=0;
return 0;
}
The loop wouldn't start again because it would just set i to 0 and then go to return 0. Once the loop is executed it won't be run again.
Note that C++ executes the code sequentially, this means that its goes through every line, executes it, then goes to the next one. This is confusing for loops because you see previous code being executed again; therefore, to solve this dilemma, think of the loop segment as a block, once this block executes, the normal sequential execution continues.
For Future reference: C++ has a beautiful feature called Multi-threading, where you can allow several code to execute in a parallel fashion. You will meet this feature sometime in the future.

my first c++ program runtime is super long like 5 - 10 minutes on a fast CPU it's a very basic c++ program [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i just dont understand whats taking so long
its the standard hello world program you write when you first start to learn a new language and its just so un-optimized
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
int main()
{
std::string hello_world = "HELLO WORLD!";
std::string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ !";
std::vector<long> positions;
std::ostringstream oss;
for(auto l : hello_world){
int position = 0;
position = letters.find(l);
positions.push_back(position);
}
for(long t = 0; t <= 100000000000; t++){
if(t%256465445 == 0){
for(auto p : positions){
oss<<letters[p];
}
}
}
std::cout<<"Hello World!";
}
This seems like it was purposefully un-optimized. I would assume that the time constraints are coming from modding a variable 100,000,000,000 times. But wait, that is not all. Not only do you mod a variable that many times, but when a variable modded to 0, you iterate another 11 times over each char in "Hello World!", or, more precisely, 389 times. That means that the last for loop needs to have done at least 100,000,004,279 calculations. How about you just remove that last for loop, because it seems useless other than to kill time, you'd be better off just doing a sleep(5).

A time counter in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I want to programme a code in C++ that makes a time-counting at the same time while we are waiting the user to enter for example the integer result we want to see.For instance we want user to enter two integers and select one of the four operations,then write down the result.Meanwhile the clock or the counting machine starts to count the seconds until the user write down the result.
Is it possible to do in C++,if it's not how can I do this?
Thanks...
C++11/14 give you even more efficient ways than the old #include<ctime> headers of C to measure time duration using certain classes like steady_clock, high_resolution_clock, etc defined in the header #include<chrono>. The following code does your job very efficiently:
#include <iostream>
#include <chrono>
using namespace std;
int main()
{
chrono::steady_clock sc; // create an object of `steady_clock` class
auto start = sc.now(); // start timer
// do stuff....
auto end = sc.now(); // end timer (starting & ending is done by measuring the time at the moment the process started & ended respectively)
auto time_span = static_cast<chrono::duration<double>>(end - start); // measure time span between start & end
cout<<"Operation took: "<<time_span.count()<<" seconds !!!";
return 0;
}
The simplest way it to use std::clock_t:
#include <iostream>
#include <cstdio>
#include <ctime>
int main()
{
std::clock_t start;
double duration;
start = std::clock(); // get current time
// Do your stuff here
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout << "Operation took "<< duration << "seconds" << std::endl;
return 0;
}
There are many ways to do that actually. This one is portable and does not need any extra library to be available. As long as you need second precision, it will be OK.