0

I need to get the milliseconds as well using only the "time.h" library.

For seconds, this is what I have:

time_t now;
time(&now);

printf("seconds since  Jan 1, 1970 %d", now);
jdl
  • 6,151
  • 19
  • 83
  • 132
  • Answers to this question mostly depend on what standards you have available... only C... or POSIX and if yes, which version(s). – PlasmaHH Jun 27 '13 at 14:58

2 Answers2

6

The <time.h> or <ctime> header files, as specified by the C and C++ standards respectively, does not support subsecond timing.

If you can use C++ and have a C++11 compatible environment, then you can get portable support with the std::chrono functionality. There's also a boost::chrono that could be used in older versions of C++.

Otherwise, you'll have to go system-specific, with for example gettimeofday in Linux/Unix and SystemTime in Windows. For other OS's, you need to look up what, if any, time functions there are.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
1

Normally one would use an OS-specific or third-party library function for this (e.g. clock_gettime on Linux). However, if you're desperate and really cannot use any other functions, you could make your program busy-wait and count processor cycles using the clock() function in time.h. This is certainly not a good idea, however--just use one of the many other header files that provide what you need.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436