Actual Millions in C ++

Is it possible to get actual milliseads since I don’t know in a C ++ program, for example System.currentTimeMillis()in Java? I know time(), but I think this is not enough to measure short times, is it?

+4
source share
3 answers

This is part of the standard language these days (several years):

Watch 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;
}
+2
source

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 other more accurate ways to measure time, but they are more dependent on which system cortex you run your programs on.

+3
source

If you have C ++ 11 support, you can take a look at std::chrono.

#include <iostream>
#include <chrono>
#include <ctime>

long fibonacci(int n)
{
    if (n < 3) return 1;
    return fibonacci(n-1) + fibonacci(n-2);
}

int main()
{
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();
    std::cout << "f(42) = " << fibonacci(42) << '\n';
    end = std::chrono::system_clock::now();

    std::chrono::duration<double> elapsed_seconds = end-start;
    std::time_t end_time = std::chrono::system_clock::to_time_t(end);

    std::cout << "finished computation at " << std::ctime(&end_time)
              << "elapsed time: " << elapsed_seconds.count() << "s\n";
}

Otherwise, you can use the std :: time style in C style as follows:

#include <ctime>
#include <iostream>

int main()
{
    std::time_t result = std::time(NULL);
    std::cout << std::asctime(std::localtime(&result))
              << result << " seconds since the Epoch\n";
}
+1
source

Source: https://habr.com/ru/post/1535152/


All Articles