Is there a simple way to calculate a time difference in ms?

Markus Freitag 3,791 Reputation points
2024-01-17T18:47:39.08+00:00

Once with local time?

Once with UTC +0 time. So I have to convert times first.

auto t_start = std::chrono::high_resolution_clock::now();
    // the work...
auto t_end = std::chrono::high_resolution_clock::now();
double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end - t_start).count();

Option 1 Check the current time // the work Check the current time, calculate the difference in ms. Not more.

Option 2: Input from database as UTC + 0 // the work Check the current time, calculate the difference in ms. First convert to UTC + 0 Not more.

What I have? VS2017 C++ Prof. https://en.cppreference.com/w/cpp/chrono/utc_clock so not possible for me.

How can I initialize this time? Then calculate the difference.

    auto t_start = // from my database           std::chrono::high_resolution_clock::now();   
	// the work...
	auto t_end = std::chrono::high_resolution_clock::now();

	double elapsed_time_ms = std::chrono::duration<double, std::milli>(t_end - t_start).count();

No problem if both side use the same time.

I need a solution for both option. Hope is clear what I need soon.

Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
{count} votes

Answer accepted by question author
  1. Minxin Yu 13,506 Reputation points Microsoft External Staff
    2024-01-19T06:34:17.73+00:00

    Hi, @Markus Freitag

    Considering your time on the PC UTC + 0

    tmFromDatabase.tm_mon = std::stoi("01")-1; // from 0 -11

    use std::chrono::system_clock::now() to get the accurate time(ms).

    	auto currentTime = std::chrono::system_clock::now();
    	auto difference_ms = std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - std::chrono::system_clock::from_time_t(std::mktime(&dbTime))).count();
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.