I found the time gap of sem_post and sem_wait is at least 50 microseconds.
sem_t gSema;
struct timeval gTv;
void *run(void *arg) {
int result;
struct timeval tv;
struct timespec nano = {0, 1};
while( 1 ) {
result = sem_trywait(&gSema);
if(result < 0) {
nanosleep(&nano, NULL);
continue;
}
if(result == 0) {
gettimeofday(&tv, NULL);
printf("waken up...elapsed time = %ld\n", (tv.tv_sec - gTv.tv_sec) * 1000000 + (tv.tv_usec - gTv.tv_usec));
}
}
return NULL;
}
void *run2(void *arg) {
int result;
struct timeval tv;
while( 1 ) {
result = sem_wait(&gSema);
if( result == 0 ) {
gettimeofday(&tv, NULL);
printf("waken up...elapsed time = %ld\n", (tv.tv_sec - gTv.tv_sec) * 1000000 + (tv.tv_usec - gTv.tv_usec));
}
}
return NULL;
}
int main(int argc, char **argv) {
pthread_t thr;
sem_init(&gSema, 0, 0);
pthread_create(&thr, NULL, run, NULL);
while( 1 ) {
sleep(1);
gettimeofday(&gTv, NULL);
sem_post(&gSema);
}
return 1;
}
At first, when I run the code with run2(), elapsed time is 50 microseconds. Then CPU usage is very low. Second, when I run the code with run() without nanosleep, elapsed time is 0 or 1. But CPU usage is 100% expectably. With nanosleep, elapsed time is 1~50 microseconds.
Is there some better method of low cpu usage AND low latency?
Aucun commentaire:
Enregistrer un commentaire