Search code examples
cexecution-time

error - time executing in C


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! :)


Solution

  • 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.