#include #include #include #include #include #include #include #include #include std::chrono::steady_clock::time_point keyTime; std::vector deltaTimes; bool spacePressed = false; //function for writing a string to a csv file int writeTextToCsv(std::string text, std::string filename) { std::ofstream fileStream; fileStream.open(filename + ".csv"); fileStream << text; fileStream.close(); return 0; } //saves the time in a global variable when the space bar is pressed void *keyPressedTime(void *) { while (!(GetKeyState(VK_SPACE) & 0x8000)) { Sleep(1); } spacePressed = true; keyTime = std::chrono::steady_clock::now(); return 0; } int main() { std::cout << "Try to hit 'space' when '5' is showing, the output will be written in a csv file\nit will now run ten times" << std::endl; //the pc time measure systematic error std::chrono::steady_clock::time_point pcTimeBegin = std::chrono::steady_clock::now(); std::chrono::steady_clock::time_point pcTimEnd = std::chrono::steady_clock::now(); int pcTimeDiff = std::chrono::duration_cast(pcTimEnd - pcTimeBegin).count(); pthread_t keyThread; for (int i = 0; i < 10; i++) { Sleep(1000); std::cout << std::endl; spacePressed = false; //start time measure for space press pthread_create(&keyThread, NULL, &keyPressedTime, NULL); std::chrono::steady_clock::time_point begin; //counter for (int num = 1; num <= 1000; num++) { Sleep(10); std::cout << "\r" << std::setprecision(2) << std::fixed << num / 100.0; if (num == 500) { //reference time point begin = std::chrono::steady_clock::now(); } if (num >= 500 && spacePressed) { break; } } //wait till space pressed void *status; pthread_join(keyThread, &status); //calculate time diff double deltaTime = (std::chrono::duration_cast(keyTime - begin).count() - pcTimeDiff) * 1.0e-6; deltaTimes.push_back(deltaTime); std::cout << "\r" << 5 + deltaTime << std::endl; //printout time diff std::cout << "Time difference = " << deltaTime << " s" << std::endl; } //output writing std::string deltaTimesStr = "reaction times in s\tmean absolute reaction time in s\n"; for (int i = 0; i < deltaTimes.size(); i++) { deltaTimesStr += std::to_string(deltaTimes[i]); if (i == 0) { deltaTimesStr += "\t"; double sum = 0; for (auto data : deltaTimes) { sum += abs(data); } deltaTimesStr += std::to_string(sum / deltaTimes.size()); } deltaTimesStr += "\n"; } writeTextToCsv(deltaTimesStr, "reaction_times"); return 0; }