Categories

Categories

Archives

Timestamp in Linux using ftime for millisecond timing

I am working on an embedded project at the moment that prints debug messages to a serial console. ?Interestingly, it seems that some of the prints are arriving out order from the actual flow of the software when they originate from the same thread.

To debug the printing problem and to add another, better layer, of debugging to the project I added a time stamp to a preprocessor definition for the existing printf() macro.

Here is the existing print macro:

#define debug_print(fmt, arg) printf (fmt, arg)
To add a time stamp we need to use the timeb struct from sys/timeb.h. Since a struct is used, we need to give it a focus. Otherwise we?ll get compile errors. It will need to be put in a false do while loop.

#define debug_print(fmt, arg) \
do { \
struct timeb tp; \
ftime(&tp); \
printf("%ld.%d: " fmt, tp.time, tp.millitm, arg); \
} while (0)

In your program you need to make sure sys/timeb.h is added and then use the new print macro.

#include <stdio.h>
#include <sys/timeb.h>
#define debug_print(fmt, arg) \
do { \
struct timeb tp; \
ftime(&tp); \
printf("%ld.%d: " fmt, tp.time, tp.millitm, arg); \
} while (0)

int main() {
while(1) {
debug_print("This is dbg print and a number: %d\n", 10);
usleep(10000);
}
return 0;
}

Enjoy!

2 comments to Timestamp in Linux using ftime for millisecond timing

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  

  

  

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.