2012-10-04 40 views
6

Después de leer this article sobre el tiempo transcurrido, escribí un código simple para calcular el tiempo de ejecución de un bucle:¿Cómo usar struct timeval para obtener el tiempo de ejecución?

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

int main (int argc, char** argv) { 
    struct timeval, tvalBefore, tvalAfter; 

    gettimeofday (&tvalBefore, NULL); 
    int i =0; 
    while (i < 1000) { 
     i ++; 
    } 

    gettimeofday (&tvalAfter, NULL); 

    printf("Time in microseconds: %0.3f microseconds\n", 
      (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) 
     ) 
    return 0; 
} 

El compilador tañido me da los siguientes errores:

print_time.c:7:16: error: expected identifier or '(' 
     struct timeval, *tvalBefore, *tvalAfter; 
        ^
print_time.c:13:17: error: use of undeclared identifier 'tvalBefore' 
     gettimeofday (&tvalBefore, NULL); 
        ^
print_time.c:19:17: error: use of undeclared identifier 'tvalAfter' 
     gettimeofday (&tvalAfter, NULL); 
        ^
print_time.c:22:12: error: use of undeclared identifier 'tvalAfter' 
         (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) 
           ^
print_time.c:22:31: error: use of undeclared identifier 'tvalBefore' 
         (float)(tvalAfter.tv_sec - tvalBefore.tv_sec) 
               ^
5 errors generated. 

no puedo averiguar qué pasa con mi código, ¿alguna idea?

+2

sacar ese coma después de 'estructura timeval' – LSerni

+3

No utilice gettimeofday para medir el tiempo de ejecución! Lea esto: http://blog.habets.pp.se/2010/09/gettimeofday-should-never-be-used-to-measure-time y esto: http://stackoverflow.com/questions/12392278/getrusage -vs-clock-gettime-vs-clock-vs-gettimeofday/12480485 # 12480485 –

+1

@ DouglasB.Staple gracias por informarme de este problema – mko

Respuesta

18

usted tiene dos errores de escritura en el código:

struct timeval, 

debería ser

struct timeval 

y después del paréntesis de printf() necesita un punto y coma.

Además, dependiendo del compilador, un ciclo tan simple podría simplemente optimizarse, dándole un tiempo de 0 microsegundos sin importar lo que haga.

Finalmente, el cálculo del tiempo es incorrecto. Solo toma en cuenta los segundos, ignorando los microsegundos. Necesita obtener la diferencia entre segundos, multiplicar por un millón, luego agregar "después" tv_usec y restar "antes" tv_usec. No ganas nada lanzando un número entero de segundos a un flotador.

Sugeriría visitar la página del manual para struct timeval.

Este es el código:

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

int main (int argc, char** argv) { 
    struct timeval tvalBefore, tvalAfter; // removed comma 

    gettimeofday (&tvalBefore, NULL); 
    int i =0; 
    while (i < 10000) { 
     i ++; 
    } 

    gettimeofday (&tvalAfter, NULL); 

    // Changed format to long int (%ld), changed time calculation 

    printf("Time in microseconds: %ld microseconds\n", 
      ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L 
      +tvalAfter.tv_usec) - tvalBefore.tv_usec 
     ); // Added semicolon 
    return 0; 
} 
+0

¡gracias por la respuesta! Fui tan descuidado – mko

+1

"... la página del manual para 'struct timeval'." ¿Qué página de hombre es esa? En mi sistema no hay una página de manual para 'struct' o 'timeval'. – neirbowj

+0

Probablemente lo tengas en 'man 2 gettimeofday' o' man 3p gettimeofday'. Aparentemente, varias páginas de manual tienden a moverse en diferentes distribuciones. – LSerni

7

Cambio:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to 
              delcare a variable with 
              no name. */ 

a:

struct timeval tvalBefore, tvalAfter; 

es menos probable (OMI) para hacer este error si hay una sola declaración por línea:

struct timeval tvalBefore; 
struct timeval tvalAfter; 

Se se vuelve más propenso a errores cuando se declaran punteros a tipos en una sola línea:

struct timeval* tvalBefore, tvalAfter; 

tvalBefore es una struct timeval* pero es una tvalAfterstruct timeval.

+0

+1 por sugerir usar la línea separada – mko

Cuestiones relacionadas