ubuntu에서 돌리면 제목 그대로 멀티스레드가 싱글 스레드보다 시간이 더 오래 걸린다고 측정이 됩니다.
그런데 Dec C++에서 돌리면 멀티스레드가 더 빠르다고 나옵니다.
싱글스레드와 멀티스레드 둘다 코드 올릴테니 뭐가 잘못됬는지 봐주시면 감사하겠습니다.
일단 멀티스레드 입니다.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
int cnt = 0;
#define NUM_THREADS 10
bool cntPrime(int num){
int ct = 0;
int i;
if(num < 2) return false;
for(i = 1; i*i<num; i++){
if(num%i == 0) ct++;
}
if(i*i == num) ct++;
if(ct == 1) return true;
else return false;
}
struct thread_args{
int myid;
long long start;
long long end;
};
void* myfunc(void *arg){
struct thread_args *myarg = (struct thread_args *) arg;
int i;
for(i = myarg->start; i <= myarg->end; i++){
if(cntPrime(i) == true)
cnt++;
}
pthread_exit(NULL);
}
int main(int argc, char* argv[]){
num = 1000000;
printf("input number: %d\n", num);
pthread_t mythread[NUM_THREADS];
struct thread_args range[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++){
range[i].myid = i;
range[i].start = (num/NUM_THREADS)*i+1;
range[i].end = (num/NUM_THREADS)*(i+1);
}
clock_t begin_time = clock();
for(int i = 0; i < NUM_THREADS; i++)
pthread_create(&mythread[i], NULL, myfunc, &range[i]);
for(int i = 0; i < NUM_THREADS; i++){
pthread_join(mythread[i], NULL);
}
clock_t end_time = clock();
printf("cnt: %d\n", cnt);
double elapsed_time = (double)(end_time - begin_time)/CLOCKS_PER_SEC;
printf("elapsed time: %f sec \n", elapsed_time);
}
다음은 싱글 스레드입니다.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
bool cntPrime(int num){
int cnt = 0;
int i;
if(num < 2) return false;
for(i = 1; i*i<num; i++){
if(num%i == 0) cnt++;
}
if(i*i == num) cnt++;
if(cnt == 1) return true;
else return false;
}
int main(int argc, char* argv[]){
int cnt = 0;
int num = 1000000;
printf("input number: %d\n", num);
clock_t begin_time = clock();
for(int i = 2; i <= num; i++){
if(cntPrime(i) == true){
cnt++;
}
}
clock_t end_time = clock();
printf("cnt: %d\n", cnt);
double elapsed_time = (double)(end_time - begin_time)/CLOCKS_PER_SEC;
printf("elapsed_time: %f sec\n", elapsed_time);
}
댓글 2
.
glibc의 clock.c를 살펴보면,
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, ..)을 통해 구현됩니다.
manual 페이지에는 다음과 같이 기술되어 있습니다.
CLOCK_PROCESS_CPUTIME_ID (since Linux 2.6.12)
Per-process CPU-time clock (measures CPU time consumed by all threads in the process).
즉, clock()을 통해서 구한 시간은 wall-clock time이 아닙니다.
참고) 링크