In C++ I wrote:
time_t tmp1, tmp2;
time(&tmp1);
sleep(1);
time(&tmp2);
std::cout << tmp2-tmp1;
But every-time I run it I see 1 printed, why the result is too perfect? shouldn't it contain some milliseconds too?
In C++ I wrote:
time_t tmp1, tmp2;
time(&tmp1);
sleep(1);
time(&tmp2);
std::cout << tmp2-tmp1;
But every-time I run it I see 1 printed, why the result is too perfect? shouldn't it contain some milliseconds too?
I recommend using std::chrono::steady_clock
to time a function:
auto const start = std::chrono::steady_clock::now();
f();
auto const stop = std::chrono::steady_clock::now();
auto const duration = stop-start;
auto const duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration);
// ^^^^^^^^^^^^
std::cout << duration_ms.count();
Your system, like many C++ systems, follows the POSIX specification for time_t
and time
. The POSIX specification says that a time_t
will contain the number of seconds since 1/1/1970.
See here for more.