Hello
In Java the following loop calculates me the results in nanoseconds and with the addition of /1000 therefore in microseconds.
Here the incomplete programm. The important part is the loop of 39 and two values which will be printed out.
Code:
for(int sx=1; sx<=39; sx++){
long startTime = java.lang.System.nanoTime();
System.out.println("Hello world");
long endTime = java.lang.System.nanoTime();
System.out.println((endTime - startTime)/1000);
}
I would like to do the same in C:
There are some examples in the internet unfortunately it returns 0 microseconds.
This is the code I have found in the internet:
Code:
/**
* Get time difference in microseconds
* */
#include <stdio.h>
#include <sys/time.h>
double time_diff(struct timeval x , struct timeval y);
int main()
{
int i;
struct timeval before , after;
gettimeofday(&before , NULL);
//Time taking task
for (i=1 ; i <= 100 ; i++)
{
printf("%d %d %d n",i, i*i, i*i*i);
}
gettimeofday(&after , NULL);
printf("Total time elapsed : %.0lf us" , time_diff(before , after) );
return 0;
}
double time_diff(struct timeval x , struct timeval y)
{
double x_ms , y_ms , diff;
x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec;
y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
I have changed this code to:
Code:
/**
* Get time difference in microseconds
* */
#include <stdio.h>
#include <sys/time.h>
double time_diff(struct timeval x , struct timeval y);
int main()
{
int i;
struct timeval before , after;
//Time taking task
for (i=1 ; i <= 39 ; i++)
{
gettimeofday(&before , NULL);
printf("Hello world\n");
gettimeofday(&after , NULL);
printf("Total time elapsed : %.0lf us\n" , time_diff(before , after) );
}
return 0;
}
double time_diff(struct timeval x , struct timeval y)
{
double x_ms , y_ms , diff;
x_ms = (double)x.tv_sec + (double)x.tv_usec;
y_ms = (double)y.tv_sec + (double)y.tv_usec;
diff = (double)y_ms - (double)x_ms;
return diff;
}
This is another example:
Again 0 value.
Code:
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
struct timeval start, end;
long mtime, seconds, useconds;
for(int sx=1; sx<=39; sx++){
gettimeofday(&start, NULL);
printf("Hello world");
gettimeofday(&end, NULL);
printf("Elapsed time: %ld microsecons\n", end.tv_usec - start.tv_usec);
}
return 0;
}
Any idea?
Thx,
Troix