Catching system time in C
I want to take 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 handle but the way I've tried using time.h
the time is fixed when I call anywhere in my main
.
4
2 answers
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
2
Author: Isvaldo Fernandes, 2015-02-21 06:58:02
See if it solves 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 unzip 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);
}
2
Author: Maniero, 2018-09-14 15:39:19