initial checkin (gettimeofday example)
[my-code/beginners.git] / time-example.c
diff --git a/time-example.c b/time-example.c
new file mode 100644 (file)
index 0000000..3fada4a
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * example of gettimeofday usage
+ *
+ */
+
+#include <stdio.h>
+#include <sys/time.h>
+#include <time.h> // only needed for time command (random seed)
+#include <stdlib.h>
+
+int main(int argc,char **argv) {
+
+  struct timeval foo1;
+  struct timeval foo2;
+  int sec,usec;
+  int i;
+
+  srand(time(NULL)); // random seed
+
+  printf("time 1:\n");
+  gettimeofday(&foo1,NULL);
+  printf("seconds: %d \t usec: %d\n",(int)foo1.tv_sec,(int)foo1.tv_usec);
+
+  while(i<rand()) i++;
+
+  gettimeofday(&foo2,NULL);
+  printf("time 2:\n");
+  printf("seconds: %d \t usec: %d\n\n",(int)foo2.tv_sec,(int)foo2.tv_usec);
+
+  sec=foo2.tv_sec-foo1.tv_sec;
+  sec=(foo2.tv_usec<foo1.tv_usec)?sec-1:sec;
+  usec=(foo2.tv_usec<foo1.tv_usec)?1000000-foo1.tv_usec+foo2.tv_usec
+                                  :foo2.tv_usec-foo1.tv_usec;
+  printf("delta t = %d sec %d usec\n",sec,usec);
+
+  return 1;
+}