So I have 2 programs that do the same things, one written in C and the other in Java. They both create 50 threads and wait for all of them to finish, then terminates.
In order to get a feel for the time difference between the 2 programs, I used the 'time' command in Linux to get the execution time.
For the C program, total execution time was 0.020 seconds, while it took the Java version 0.663 seconds to complete.
I've tried searching for an answer but all I've found were some articles such as (these two ) saying that Java was actually faster than C, which I thought was nonsense, so I would really appreciate if anyone could clarify this for me.
Thanks.
This is what the C code looks like.
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#define N 50
void* tproc(void *arg) {
printf("Thread %d\n", *((int *) arg));
return NULL;
}
int main(int argc, char * argv[]) {
int i;
int targ[N];
pthread_t tid[N];
for(i = 0; i < N; i++) {
targ[i] = i;
if(pthread_create(&(tid[i]), NULL, &tproc, &targ[i]) != 0) {
printf("Can't create thread %d\n", i);
return 1;
}
}
for(i = 0; i < N; i++) {
if(pthread_join(tid[i], NULL) != 0) {
printf("Can't join thread %d\n", i);
}
}
return 0;
}
This is what the Java code looks like.
import java.util.concurrent.*;
class MyThread extends Thread {
static final int N = 50 ;
int arg;
public MyThread(int arg) {
this.arg = arg;
}
public void run() {
System.out.println("Thread " + arg);
}
public static void main(String [] args) {
MyThread[] tid = new MyThread [N] ;
for(int i = N-1; i >= 0; i--) {
tid[i] = new MyThread(i);
tid[i].start();
}
for(int i = 0; i < N; i++) {
try { tid[i].join(); }
catch(InterruptedException e) { }
}
}
}