|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?注册
x
小弟最近遇到一些代码,关于操作系统的,不时很懂。。
请问有高人可以解答一下吗?
请问为什么第二个程序效率为什么比第一个高。。(找质数)
第一个
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define MAX 100000
unsigned long int primes[MAX];
static void *primefunction() {
static unsigned long int i = 3, j, c = 0;
printf("2\n");
while (c < MAX) {
for (j = 0; j < c; j++)
if (i % primes[j] == 0)
goto trynext;
// hier angekommen: i ist prim
primes[c++] = i;
printf("%ld\n", i);
trynext: i += 2;
}
return NULL;
}
int main (void) {
pthread_t prime_thread;
pthread_create( &prime_thread, NULL, &primefunction, NULL );
while (getchar() != '\n') ;
pthread_cancel(prime_thread);
exit(0);
}
第二个
#include <stdio.h>
#include <stdlib.h>
#include <sys/select.h>
#define MAX 100000
unsigned long int primes[MAX];
int check_stdin () {
struct timeval timeout ;
fd_set readmask ;
int no_of_descriptors ;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
FD_ZERO (&readmask );
FD_SET ( fileno ( stdin ), &readmask );
no_of_descriptors = select ( FD_SETSIZE , &readmask , NULL , NULL , &timeout );
if ( no_of_descriptors >= 0)
return no_of_descriptors ;
else {
perror (" select error ");
exit ( EXIT_FAILURE );
}
}
int main(void) {
static unsigned long int i = 3, j, c = 0;
printf("2\n");
while (c < MAX) {
for (j = 0; j < c; j++) {
if (check_stdin() > 0 && getchar() == '\n')
return EXIT_SUCCESS;
if (i % primes[j] == 0)
goto trynext;
}
// hier angekommen: i ist prim
primes[c++] = i;
printf("%ld\n", i);
trynext: i += 2;
}
return EXIT_SUCCESS;
}
非常感谢阿。。 |
|