Olof Olof - 29 days ago 4x
C Question

Wrong time from clock

I have a program that counts the time to send or receive a amount of data. When I receive the data the clocks says it only takes about half of the time it actually takes.

Output from the terminal that recives the data:

Amount of data recived: 60296112/300000000
Time: 4
Start time: 3269
End time: 4849790
Clocks per sec: 1000000

And the output from the terminal that sends the data:

Sent 300000000 bytes of data
Time to send was 10.793425

The terminal that sends the data will send a stop signal after it has sent all other data. When I watch the terminal that receives the data I can see that it starts counting when the other terminal starts sending data and I can see it print out output from
way longer that the output says it does.

My code for the receive part:

static void recive_sock(int socket_fd,char *buffert, size_t buffert_size, struct sockaddr *other, socklen_t *other_size){
clock_t start_t, end_t;
long int total_time = 0;
printf("Listning for data\n" );
int run = 1;
char start = 1;
int amount = 0;
int recive_length;

recive_length = recvfrom(socket_fd, buffert, buffert_size, 0, other, other_size );
if(recive_length < 0){
die("Recvfrom failed");
if(strncmp(buffert, "HELLO!", 6) == 0){
amount += recive_length;
if(start == 1){
start = 0;
start_t = clock();
printf("Start: %ld\n",start_t );
printf("%ld\n",clock() );
else if (strncmp(buffert, "die", 3) == 0) {
run = 0;
end_t = clock();
printf("End %ld\n",end_t );
total_time = (end_t - start_t) / CLOCKS_PER_SEC;
printf("Amount of data recived: %d/%d\nTime: %ld\nStart time: %ld\nEnd time: %ld\n,Clocks per sec: %ld", amount, AMOUNT, total_time, start_t, end_t, CLOCKS_PER_SEC);


The function clock will return the CPU time which is probably not what you are looking for, instead you want to use something like gettimeofday. Then you can compare the time before and after to get the time elapsed. Here is a simple example on how to measure time with gettimeofday:

#include <stdio.h>
#include <sys/time.h>                // for gettimeofday()

int main(void) {
    int i = 0;
    int j = 0;
    int sum = 0;
    struct timeval t1, t2;
    double elapsedTime;

    // start timer
    gettimeofday(&t1, NULL);

    // do something here
    for (i = 0; i < 10000; i++) {
        for (j = 0; j < 10000; j++) {
            sum *= i+j;

    // stop timer
    gettimeofday(&t2, NULL);

    // compute and print the elapsed time in millisec
    elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;
    elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;
    printf("%.3f ms elapsed\n", elapsedTime);

    return 0;