Jump to content

[C][Dúvida] Como calcular tempo em milisegundos RESOLVIDO


rgcaldas

Recommended Posts

Boas

Mais uma dúvida, eu preciso de calcular o tempo que uma função demora a correr em milisegundos.

Já tentei agarrar o tempo de inicio e de fim

  (void) time(&inicio);
  (void) time(&fim);

E mostrar a diferença

difftime(fim,inicio);

Mas isto só me conta o tempo em segundos e não em milisegundos.

Alguém já fez algo do género, ou tem alguma ideia, já tou farto de googlar e não me safo.

Obrigado

Link to comment
Share on other sites

Em Unix, penso que a função gettimeofday deve servir.

É mesmo em linux, e safei-me com essa, apesar que dizerem por ai que não é muito fiável.

Se houver mais alguèm interessado fica aqui a solução:

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

#define MICRO_PER_SECOND 1000000 
// Os 1000000 e so porque quero que os milisegundos aparecam como decimal dos segundos
// o membro tv_use da struct timeval vem em microsegundos


int main(int argc,char* argv[])
{
    struct timeval start_time;
    struct timeval stop_time;
    float time_diff;

    gettimeofday( &start_time, NULL );
    funcao(); // qualquer coisa que queiram medir
    gettimeofday( &stop_time, NULL );

     time_diff = (float)(stop_time.tv_sec - start_time.tv_sec);
     time_diff += (stop_time.tv_usec - start_time.tv_usec)/(float)MICRO_PER_SECOND; 
     printf("\nfuncao executada em %f ms",time_diff);

    return 0;
}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.