I am trying to format my time stamp in ISO 8601 with microseconds in C.
Like this 2014-11-06T10:34:47.123456Z, but I cant seem to get microseconds.
Any help would be greatful.
#pragma warning(disable:4996)
#define _CRT_SECURE_NO_WARNING
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#define SIZE 256
int
main(void)
{
char buffer[SIZE];
time_t curtime;
/* Get the current time. */
curtime = time(NULL);
strftime(buffer, sizeof buffer, "ISO 8601 %Y-%m-%dT%H:%M:%S\n", gmtime(&curtime));
fputs(buffer, stdout);
getchar();
return 0;
}
Related
I want to create an overlay in terminal
This Q&D shows the time in right/bottom
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <termios.h>
#include <error.h>
#include <unistd.h>
#include <time.h>
static char termbuf[2048];
int main()
{
char *termtype = getenv("TERM");
time_t timer;
char buffer[26];
struct tm* tm_info;
if (tgetent(termbuf, termtype) < 0) {
error(EXIT_FAILURE, 0, "Could not access the termcap data base.\n");
return 1;
}
int lines = tgetnum("li");
int columns = tgetnum("co");
int pos=1;
while (1) {
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
printf("\033[s");
fflush(stdout);
printf("\033[%d;%dH%s\n", lines - 2, columns - 20, buffer);
printf("\033[u");
sleep(1);
}
return 0;
}
it is compiled with:
$ gcc time-overlay.c -ltermcap -o time-overlay
And to use it:
$ ./time-overlay &
It will show:
2017-04-29 12:29:15
And keep updating time.
To stop:
$ fg
Ctrl+C
But, is there a better way to do that with some library that abstracts low level calls (like save restore cursor position or print in some line/col)
I want to keep existing terminal output (so curses with initscr() will not work)
This is how you would use termcap (or anything provides a termcap interface, e.g., ncurses):
#include <stdio.h>
#include <stdlib.h>
#include <termcap.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define MAXTERM 2048
#define EndOf(s) (s) + strlen(s)
int
main(void)
{
char termbuf[MAXTERM];
char workbuf[MAXTERM];
char *working = workbuf;
int lines, columns;
char *save_cursor, *move_cursor, *restore_cursor;
if (tgetent(termbuf, getenv("TERM")) < 0) {
fprintf(stderr, "Could not access the termcap database.\n");
return EXIT_FAILURE;
}
lines = tgetnum("li");
columns = tgetnum("co");
save_cursor = tgetstr("sc", &working);
move_cursor = tgetstr("cm", &working);
restore_cursor = tgetstr("rc", &working);
while (1) {
time_t timer;
char buffer[1024];
struct tm *tm_info;
time(&timer);
tm_info = localtime(&timer);
strcpy(buffer, save_cursor);
sprintf(EndOf(buffer), tgoto(move_cursor, columns - 20, lines - 2));
strftime(EndOf(buffer), 26, "%Y-%m-%d %H:%M:%S", tm_info);
strcat(buffer, restore_cursor);
write(fileno(stderr), buffer, strlen(buffer));
sleep(1);
}
return EXIT_SUCCESS;
}
It could still be improved since the various strings returned from tgetstr are not guaranteed to be provided by all terminal descriptions, and of course, termcap applications always have buffer-overflow issues to work around.
I'm trying to record the time my program takes to finish in seconds, with sub-second accuracy.
I'm not recording CPU time or cycles, I simply want to be able to mark a start point (Wall Clock time), then at the end of my program mark a finish (Wall Clock time), and calculate the delta.
Have a look at the function:
int clock_gettime(clockid_t clk_id, struct timespec *tp);
The function will fill the structure struct timespec you provide. Here is its definition:
struct timespec {
time_t tv_sec; /* secondes */
long tv_nsec; /* nanosecondes */
};
So the returned time in nanosecondes is: tp->tv_sec * 1e9 + tp->tv_nsec.
You can find all the possible clk_id in the man. I would recommend you to use CLOCK_MONOTONIC as it guarantees you that the time given will always be continuous, even if the time of the system is modified.
Just call time(NULL) to get the current time and use difftime to calculate the time between two points.
#include <time.h>
// ...
time_t start = time(NULL);
// do stuff here
time_t end = time(NULL);
printf("Took %f seconds\n", difftime(end, start));
This displays start/end time stamps and calculates a delta in seconds.
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void print_timestamp(char *, time_t);
int main (int argc, char *argv[]) {
time_t start = time(0);
print_timestamp("Start: ", start);
sleep(2);
time_t end = time(0);
print_timestamp("End: ", end);
double diff = difftime(end, start);
printf("Elapsed: %5.2lf seconds\n", diff);
}
void
print_timestamp(char *msg, time_t time) {
struct tm *tm;
if ((tm = localtime (&time)) == NULL) {
printf ("Error extracting time stuff\n");
return;
}
printf ("%s %04d-%02d-%02d %02d:%02d:%02d\n",
msg,
1900 + tm->tm_year,
tm->tm_mon+1,
tm->tm_mday,
tm->tm_hour,
tm->tm_min,
tm->tm_sec);
}
Sample output:
Start: 2017-02-04 15:33:36
End: 2017-02-04 15:33:38
Elapsed: 2.00 seconds
You may also be able to use the time command available on (at least) Unix systems.
After compiling your program, run the command like this:
# compile your code
$ gcc foo.c -o foo
# compute the time
$ time ./foo
You can use the clock() function to record the number of ticks taken and then convert this to seconds:
#include <time.h>
#include <stdio.h>
#include <math.h>
int main () {
clock_t start_t = clock();
double a=0;
for(int i=0; i< 10000000; i++) {
a+=sqrt(a);
}
clock_t end_t = clock();
double total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
printf("Total time taken by CPU: %lf\n", total_t );
return(0);
}
how to get minute of the system time from C program? can I use gettimeoftheday?? If anyone has C program which can do this please share, I'm a newbie.Thanks
some sample code
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[30];
struct timeval tv;
time_t curtime;
gettimeofday(&tv, NULL);
curtime=tv.tv_sec;
strftime(buffer,30,"%m-%d-%Y %T.",localtime(&curtime));
printf("%s%ld\n",buffer,tv.tv_usec);
return 0;
}
You can use strftime to get only the minutes part :
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char buffer[0x100];
time_t curtime;
// Don't forget to check the return value !
curtime = time(NULL);
if (curtime == -1)
{
perror("time()");
return 1;
}
strftime(buffer,0x100,"%M",localtime(&curtime));
printf("minutes: %s\n", buffer);
return 0;
}
No need to use gettimeofday here, use it only if you want a precision better than seconds.
#include <stdio.h>
#include <time.h>
int main()
{
time_t curtime;
char buffer[30];
struct tm* tm_info;
time(&curtime);
tm_info = localtime(&curtime);
strftime(buffer, 30, "%Y-%m-%d %H:%M:%S", tm_info);
puts(buffer);
return 0;
}
%Y:- will print year
%m:- will print Month
%d:- will print day
%H:- will print Hour
%M:- will print Minute
%S:- will print Second
I am trying to make a clock in C, but the screen is not properly clearing, it just keeps printing to a new line. How am I improperly using fflush?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
while (1) {
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("%s", asctime (timeinfo));
fflush(stdout);
}
return 0;
}
This strips out the newline from the asctime string and then uses a return to push the cursor back to the start of line
#include <string.h>
int main()
{
while (1) {
time_t rawtime;
char st[30];
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
sprintf (st,"%s", asctime (timeinfo));
*(index(st,'\n'))='\0';
printf("\r%s",st);
flush(stdout);
sleep(1);
}
return 0;
}
This one has the advantage that it will work from the current location on the screen, no matter what that is. I added a label to print "The time is: " in order to show this. It does this by back spacing from the end of the time string rather than going to an absolute screen position or column. Caveat: The hack to get sleep() under Visual C has not been tried.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#ifdef _MSC_VER
#include <windows.h>
#define sleep(T) Sleep((T) * 1000)
#else
#include <unistd.h>
#endif
int main(void)
{
char buf[42];
time_t the_time[1];
int i, len;
printf("The time is: ");
for (;;) {
time(the_time);
len = strlen(strcpy(buf, asctime(localtime(the_time)))) - 1;
printf("%.*s", len, buf);
for (i = 0; i < len; i++) putchar('\b');
fflush(stdout);
sleep(1);
}
return 0;
}
This will do it... (uses an evil windows call SetConsoleCursorPosition(), but does the trick)
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gotoxy(int x, int y);
int main()
{
while (1) {
time_t rawtime;
struct tm * timeinfo;
gotoxy(0,0);//set to the upper left hand corner
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ("%s", asctime (timeinfo));
fflush(stdout);
}
return 0;
}
void gotoxy(int x, int y)
{
COORD pos = {x, y};
HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(output, pos);
}
Try this for POSIX:
#!/usr/bin/tcc -run
#include <stdio.h>
#include <termios.h>
int main ()
{
struct termios ts0, ts1;
char cls [FILENAME_MAX];
FILE *f;
f = popen ("tput clear", "r");
fgets (cls, FILENAME_MAX, f);
pclose (f);
tcgetattr (0, &ts0);
ts1 = ts0;
ts1.c_lflag &= ~ECHO;
ts1.c_lflag &= ~ICANON;
tcsetattr (0, TCSAFLUSH, &ts1);
fputs (cls, stdout);
while (1) putchar (getchar ());
tcsetattr (0, TCSAFLUSH, &ts0);
return 0;
}
I have tried the function:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);
printf ("%ld hours since January 1, 1970", seconds/3600);
return 0;
}
It is useful but it returns the time in number of seconds since 1970. In my case, I would like to obtain a result with more precision, to distinguish two events happening in the same second. Is it possible to do that?
Use gettimeofday(3). It allows you to get the time in microseconds.
#include <stdio.h>
#include <sys/time.h>
int main(int argc, char **argv)
{
struct timeval tv = { 0 };
gettimeofday(&tv, NULL);
printf("sec: %ld usec: %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
or with clock_gettime():
#include <stdio.h>
#include <time.h>
int main(int argc, char **argv)
{
struct timespec ts = { 0 };
clock_gettime(CLOCK_REALTIME, &ts);
printf("sec: %ld nsec: %ld\n", ts.tv_sec, ts.tv_nsec);
return 0;
}
Try clock_gettime . It gives additional info in nanoseconds.
Basic Standard C does not describe any calendar time functions with a resolution better than 1 second.
You have to use extensions.
For POSIX, try gettimeofday() (obsolescent) clock_gettime().
For Windows, apparently, you can use GetSystemTime().