I'm not sure whether what this is true or not, but in my code, I'm printing the value of a variable called currentTime which records the number of seconds since the application was run. The currentTime variable is recorded as time(NULL) - epocTime where epocTime was set to time(NULL) at the beggining of the code. even though currentTime is of type double, it prints out as 1.0000, 2.0000, 3.0000, and so on as my application runs. However it never has a non integer value. Is it possible for me to change how I record time, so that the milliseconds are also recorded, for example is there a parameter I can give the time() method to make it record milliseconds.
Asked
Active
Viewed 3,403 times
0
-
5http://en.cppreference.com/w/cpp/chrono – Cthulhu Jan 08 '15 at 17:37
-
1`time()` gives you integers. It doesn't matter what you assign and convert that value to. It cannot magically obtain microseconds resolution. – Lightness Races in Orbit Jan 08 '15 at 17:41
1 Answers
1
time()
almost always returns an integral type that contains the number of seconds since Jan 1, 1970. There's not much you can do with time()
itself to change that.
Instead you should look into std::chrono::steady_clock
:
#include <chrono>
#include <thread>
#include <iostream>
int main() {
auto start = std::chrono::steady_clock::now();
// Some work
std::this_thread::sleep_for(std::chrono::seconds(1));
auto end = std::chrono::steady_clock::now();
auto elapsed = end - start;
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count() << " milliseconds\n";
}

Bill Lynch
- 80,138
- 16
- 128
- 173
-
1_"Not much"_ Or, in fact, nothing. And [your `std::clock` suggestion is simply wrong](http://kera.name/articles/2011/03/tomalaks-tuesday-tip-11-sleep-your-way-to-success/). – Lightness Races in Orbit Jan 08 '15 at 17:42
-
1@LightnessRacesinOrbit: I always forget which of the older clocks return wall time or cpu time and if they fail miserably when your process switches processes. So let's just delete that part of the answer. Thank you the for the link though, and I may beat that into my memory one of these days. – Bill Lynch Jan 08 '15 at 17:44