0

I'm working in first step of a Project and I have to calculate the executing time of a Summation and a multiplication... I wrote the next code for the summation:

#include <stdio.h>
#include <time.h>

int main(int argc, char const *argv[]) {
  long muestras = 100000000;
  long resultado=0;
  float inicial = clock();
  printf("Tiempo inicial: %f\n",inicial);
  for(int i = 1; i <muestras;i+=1){
    resultado = resultado + i;
  }
  float final = clock();
  printf("Tiempo final: %f\n",final);
  float total = (final-inicial)/((double)CLOCKS_PER_SEC);
  printf("tiempo = %f",total);
  //printf("tiempo = %f",((double)clock() - start));
  printf("\n");
  printf("resultado = %d",resultado);
  return 0;
}

and work perfectly, but I wrote the next code for the multiplication, and the initial and final time is 0... I don't know why, I can't understand ...

#include <stdio.h>
#include <time.h>

int main(int argc, char const *argv[]) {
  long muestras = 10;
  long long resultado=1;
  float inicial = clock();
  printf("Tiempo inicial: %f\n",inicial);
  for(int i = 1; i <muestras;i+=1){
    if (resultado>20) {
      resultado = (resultado * i)/20;
    }else{
      resultado = resultado * i;
    }
  }
  float final = clock();
  printf("Tiempo final: %f\n",final);
  float total = (final-inicial);
  ///((double)CLOCKS_PER_SEC);
  printf("tiempo = %f",total);
  //printf("tiempo = %f",((double)clock() - start));
  printf("\n");
  printf("resultado = %lli",resultado);
  return 0;
}

I know that have overflow, but no matter what size of samples take, it's the same result.... please help ... sorry for my bad english, greats from Colombia! :)

2 Answers2

1

The return value from clock is of type clock_t, not float. Also, the return value is not seconds or anything such, but "clocks", which you can convert to seconds by dividing by clocks per sec.

You should do something like this instead:

clock_t initial = clock();
...
clock_t final = clock();
double total = (final - initial) / (double)CLOCKS_PER_SEC;
printf("time delta = %f", total);

Note that there is no way of printfing a value of type clock_t correctly.

Community
  • 1
  • 1
  • thanks for your answer, it Works for the summation, but I have the same problem with the multiplication .... I increase "muestras" to 100 but the answer is 0 and the time 0 too ... – Viviana Leyva Cifuentes Apr 14 '17 at 18:12
0

The return value from clock() is of type clock_t not float, and it represents the number of ticks since the beginning of the program. You should subtract them and then convert to double to divide by CLICKS_PER_SEC, as in Antti's answer.

Also, your multiplication program only executes 10 muestras, which means it may entirely finish in the first clock tick. Increase that to a large number and you may see different elapsed time.

David Jeske
  • 2,306
  • 24
  • 29