c - Getting the time difference between two different times -
gcc (gcc) 4.7.2 c89 hello,
i have developed sample program should difference between start time , end time. use seconds calculate how many days has elapsed between 2 times.
this logging application after user specified number of days. logs rolled on , new start time set. user can decide how many days log replaced.
i added small sleep general idea, logging days.
is best , portable (linux/windows) way this? potential pitfalls in design?
many suggestions,
#include <time.h> #include <stdio.h> #include <string.h> int main(void) { time_t start_timestamp; time_t end_timestamp; struct tm time_days; double seconds = 0; size_t cumulative_days = 0; #define format_time_size 64 char format_time[format_time_size]; #define day 3600 /* seconds in 1 day */ #define max_days 10 /* roll on log after 10 days */ /* current time of starting application */ time(&start_timestamp); time_days = *localtime(&start_timestamp); /* print current time @ start */ memset(format_time, 0, sizeof format_time); strftime(format_time, sizeof format_time, "%c", &time_days); printf("timestamp start [ %s ]\n", format_time); /* simulate simple sleep. logging many days */ sleep(10); /* current time after delay print results */ time(&end_timestamp); time_days = *localtime(&end_timestamp); memset(format_time, 0, sizeof format_time); strftime(format_time, sizeof format_time, "%c", &time_days); printf("timestamp end [ %s ]\n", format_time); /* current difference in seconds */ seconds = difftime(end_timestamp, start_timestamp); printf("seconds elapsed [ %f ]\n", seconds); /* calculate how many days have elapsed */ cumulative_days = day * seconds; /* going */ if(cumulative_days <= max_days) { printf("delete log , start over\n"); } else { printf("not there yet, keep appending current log\n"); } return 0; }
an alternative , arguably easier way use current day extension in log filename mylog.22, way automatic rollover , keep last month of logs.
Comments
Post a Comment