I'm trying to find the time slice of a program, first I assigned to each of the threads an ID to help identify them in their f
function. In the f
function, I used the timeval
struct to check for the start and finish times, subtract them from each other and multiply by 1000 to convert to ms.
The result I expected (for example on 2 threads) was an infinite loop that would print that time for each thread. The result I got was an infinite loop, only going through the second thread and the time is always 0 or 0.001ms (why?).
I'd appreciate hints on how I should think of the solution \ what I've done wrong?
The code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h> //For gettimeofday()
int i; //Global variable to act as an ID for the threads
void *f(void *p);
void main(int argc, char *argv[]){
if(argc < 2){
perror("Illegal input");
exit(1);
}
int num;
num = atoi(argv[1]);
int index[num];
pthread_t arr[num];
for(i=0; i<num; i++){
index[i] = i+1;
pthread_create (&arr[i], NULL, f, (void *) &index[i]);
}
for(i=0; i<num; i++) //Wait for all threads to finish
pthread_join(arr[i], NULL);
}
void *f(void *p){
int pid = *((int *)p); //Thread ID
struct timeval start, finish;
double elapsedTime;
while(1){
gettimeofday(&start, NULL);
gettimeofday(&finish, NULL);
elapsedTime = (finish.tv_sec - start.tv_sec) * 1000.0; //sec to ms
elapsedTime += (finish.tv_usec - start.tv_usec) / 1000.0; // us to ms
fprintf(stdout, "Time slice for thread %d = %lf ms.\n", pid, elapsedTime);
}
}
The output (infinite loop):
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.000000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Time slice for thread 2 = 0.001000 ms.
Try:
Note that calculating difference between two calls of
gettimeofday
makes little sense - the clock is not monotonic. In anything serious useclock_gettime(CLOCK_MONOTONIC
for a monotonic clock.