Taking system time in C

4

I want to get the start and end time of a for . Ex.:

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

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  int i, j;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );
  for (j = 0; j < 10; j ++)
        for (i = 0; i < 138763431; i ++);
  printf ( "\nCurrent local time and date: %s", asctime (timeinfo) );

  return 0;
}

I'm already using GetTickCount() for seconds. I would give it to manipulate but the way I already tried using time.h the time is fixed when I call anywhere in my main .

    
asked by anonymous 04.11.2014 / 23:42

2 answers

2

A "simple" way to calculate the time difference using little code

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

int main(int arc, char *argv[])
{
 clock_t t1, t2; // duas variáveis para guardar o registro clock

 t1 = clock(); // pega esse instante

 int i;

 for(i = 0;i < 500000 ;i++)
 {
      int x = 90; 
 }

 t2 = clock(); // pega esse

 // tira a diferença e divide por 1000000.0F

 float diff = (((float)t2 - (float)t1) / 1000000.0F ); // mile segundos
 printf("%f",diff);

 return 0;
 } 

This project demonstrates the use of this calculation

    
21.02.2015 / 07:58
2

See if you resolve what you want with the code I found in the OS .

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

int main() { 
    struct timeb start, end;
    int diff;
    int i = 0;
    ftime(&start);

    while(i++ < 999) {
        /*gastando tempo*/
        printf(".");    
    }

    ftime(&end);
    diff = (int) (1000.0 * (end.time - start.time) + (end.millitm - start.millitm));

    printf("\nGastou %u milisegundos\n", diff);
    return 0;
}

You can unlink timeb . See in this answer :

void getCurrTimeString(TCHAR* mytime) {
    _timeb myTime;
    struct tm * timeinfo;

    _ftime64_s( &myTime );
    time_t rawtime = myTime.time;
    unsigned short myMillis = myTime.millitm;
    timeinfo = localtime ( &rawtime );
    _stprintf(mytime,_T("%d-%02d-%02dT%02d:%02d:%02d.%03d"),
        (1900+timeinfo->tm_year),
        (timeinfo->tm_mon+1),
        timeinfo->tm_mday,
        timeinfo->tm_hour,
        timeinfo->tm_min,
        timeinfo->tm_sec,
        myMillis);
}

I placed GitHub for future reference .

    
05.11.2014 / 01:22