First of I do not want to use #include <ctime>
and time(0);
the time(0); is with ctime. What I want is if say the time is 10:13:40:23 AM I would get the value of 23. I looked around the web for a while and could not find anything besides ctime, but ctime is for the system time in milliseconds meaning that the value is really high. Another example would be 12:56:30:192 PM and I would get the value of 192. thanks for any help :).
Asked
Active
Viewed 364 times
1

NoahGav
- 251
- 4
- 12
-
This is platform dependent. What platform are you using? – Ed Heal Nov 03 '15 at 17:17
-
Windows 7. Also I am using minGW compiler. – NoahGav Nov 03 '15 at 17:18
-
1note that you'll get exactly what you're after, if you just mod by `1000` – BeyelerStudios Nov 03 '15 at 17:20
-
6There is now [`
`](http://en.cppreference.com/w/cpp/header/chrono) in the standard library – NathanOliver Nov 03 '15 at 17:20 -
I tried
and it didn't compile. It says something about c++ 2011? – NoahGav Nov 03 '15 at 17:21 -
What @BeyelerStudios said. It doesn't matter if the value `ctime` returns is large. – Carey Gregory Nov 03 '15 at 17:21
-
If I mod it by 1000 it returns the same number if I run it in a loop. – NoahGav Nov 03 '15 at 17:23
-
Because you're using a modern computer. A simple loop will execute many times in a millisecond. – Carey Gregory Nov 03 '15 at 17:24
-
3@MrQandA _"I tried
and it didn't compile."_ `std::chrono` is available since C++11, which is the current standard. You might need to enable it using the `-std=c++11` option of your compiler. – πάντα ῥεῖ Nov 03 '15 at 17:26 -
[Here](http://ideone.com/uXlqWy) is an example that gives you different numbers in the loop. Note the use of `usleep` which causes the computer to pause for a given number of microseconds. – R_Kapp Nov 03 '15 at 17:28
-
@Paul R supposed duplicates uses either boost or c (as opposed to c++) so not really helpful here – Eran Nov 03 '15 at 18:16
1 Answers
5
With C++ 11, using std::chrono library.
#include <iostream>
#include <chrono>
int main()
{
auto now = std::chrono::system_clock::now();
std::chrono::milliseconds ms_since_epoch = std::chrono::duration_cast< std::chrono::milliseconds >(now.time_since_epoch());
std::chrono::seconds seconds_since_epoch = std::chrono::duration_cast< std::chrono::seconds >(now.time_since_epoch());
std::cout << (ms_since_epoch - seconds_since_epoch).count() << std::endl;
return 0;
}
On seconds thought, modulo 1000 would have done the same as subtracting the seconds. Anyway, given that the epoch is canonical (has 00 for seconds and 000 for milliseconds), that part of it is indeed the actual milliseconds measurement of the now moment.

Eran
- 2,324
- 3
- 22
- 27