select performance

hitkey use select

Posted on

set millisecond to 1 cost cpu 98% on
Model Name: MacBook
Model Identifier: MacBook1,1
Processor Name: Intel Core Duo
Processor Speed: 1.83 GHz
Number Of Processors: 1
Total Number Of Cores: 2
L2 Cache: 2 MB
Memory: 1 GB
Bus Speed: 667 MHz


#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <termios.h>
#include <stdio.h>

static struct termios orig_termios;

static void reset_terminal_mode()
{
tcsetattr(0, TCSANOW, &orig_termios);
}

static void set_conio_terminal_mode()
{
struct termios new_termios;

/* take two copies - one for now, one for later */
tcgetattr(0, &orig_termios);
memcpy(&new_termios, &orig_termios, sizeof(new_termios));

/* register cleanup handler, and set the new terminal mode */
atexit(reset_terminal_mode);
cfmakeraw(&new_termios);
tcsetattr(0, TCSANOW, &new_termios);
}

static int getch()
{
static int r;
static unsigned char c;
if ((r = read(0, &c, sizeof(c))) < 0) {
return r;
} else {
return c;
}
}

int kbhit(unsigned int millisecond)
{
static int r = 0;
static struct timeval tv = { 0L, 0L };
fd_set fds;
FD_SET(0, &fds);
tv.tv_sec = millisecond / 1000000 ;
tv.tv_usec = millisecond % 1000000;
if ( select(1, &fds, NULL, NULL, &tv) )
return getch();
return 0;
}

int main(int argc, char *argv[])
{
int count = 0;
unsigned int millisecond =0;
if ( argc == 2 )
millisecond = atoi(argv[1]);
printf("time:%u\n",millisecond);
set_conio_terminal_mode();

while (!kbhit(millisecond)) {
/* do some work */
//printf("count:%d\n",count++);
}
//(void)getch(); /* consume the character */
}

廣告