📄 input.cpp
字号:
// posix.cpp
// includes
#include <ctime>
#if defined(_WIN32) || defined(_WIN64)
#include <windows.h>
#else // assume POSIX
#include <sys/resource.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include "input.h"
#include "util.h"
// prototypes
#if !defined(_WIN32) && !defined(_WIN64)
static double duration(const struct timeval *tv);
#endif
// functions
// input_available()
bool input_available()
{
#if defined(_WIN32) || defined(_WIN64)
static bool init = false, is_pipe;
static HANDLE stdin_h;
DWORD val;
// val = 0; // needed to make the compiler happy?
// have a look at the "local" buffer first, *this time before init (no idea if it helps)*
if(stdin->_cnt > 0)
return true;
// input init (only done once)
if(!init)
{
init = true;
stdin_h = GetStdHandle(STD_INPUT_HANDLE);
is_pipe = !GetConsoleMode(stdin_h, &val);
if(!is_pipe)
{
SetConsoleMode(stdin_h, val & ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT));
FlushConsoleInputBuffer(stdin_h); // no idea if we can lose data doing this
}
}
// different polling depending on input type
// does this code work at all for pipes?
if(is_pipe)
{
if(!PeekNamedPipe(stdin_h, NULL, 0, NULL, &val, NULL))
{
return true;
}
return val > 0; // != 0???
}
else
{
GetNumberOfConsoleInputEvents(stdin_h, &val);
return val > 1;
}
return false;
#else // assume POSIX
int val;
fd_set set[1];
struct timeval time_val[1];
FD_ZERO(set);
FD_SET(STDIN_FILENO, set);
time_val->tv_sec = 0;
time_val->tv_usec = 0;
val = select(STDIN_FILENO + 1, set, NULL, NULL, time_val);
return val > 0;
#endif
}
// now_real()
double now_real()
{
#if defined(_WIN32) || defined(_WIN64)
return double(GetTickCount()) / 1000.0;
#else // assume POSIX
struct timeval tv[1];
struct timezone tz[1];
tz->tz_minuteswest = 0;
tz->tz_dsttime = 0; // DST_NONE not declared in linux
gettimeofday(tv, tz);
return duration(tv);
#endif
}
// now_cpu()
double now_cpu()
{
#if defined(_WIN32) || defined(_WIN64)
return double(clock()) / double(CLOCKS_PER_SEC); // OK if CLOCKS_PER_SEC is small enough
#else // assume POSIX
struct rusage ru[1];
getrusage(RUSAGE_SELF, ru);
return duration(&ru->ru_utime);
#endif
}
// duration()
#if !defined(_WIN32) && !defined(_WIN64)
static double duration(const struct timeval *tv)
{
return double(tv->tv_sec) + double(tv->tv_usec) * 1E-6;
}
#endif
// end of posix.cpp
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -