Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actual millis in a C++

Tags:

c++

time

chrono

Is it possible to get the actual millis since I-don't-know in a C++-programm like System.currentTimeMillis() in Java? I know time(), but I think it's not exactly enough to measure short times, is it?

like image 364
PEAR Avatar asked Apr 05 '14 10:04

PEAR


2 Answers

It's part of the language standard these days (some years now):

See it Live On Coliru

#include <chrono>
#include <iostream>

int main()
{
    using namespace std::chrono;

    auto epoch = high_resolution_clock::from_time_t(0);
    // ...
    auto now   = high_resolution_clock::now();

    auto mseconds = duration_cast<milliseconds>(now - epoch).count();

    std::cout << "millis: " << mseconds;
}
like image 109
sehe Avatar answered Sep 25 '22 00:09

sehe


In C++ you also have clock()

#include <time.h>

...

clock_t start = clock();
... some processing ...
clock_t stop = clock();

double elapsed = double(stop - start) / CLOCKS_PER_SEC;

There are also other more accurate ways of measure timings, but they are more dependent on which king of system you're running your programs on.

like image 26
6502 Avatar answered Sep 27 '22 00:09

6502