jj172
jj172

Reputation: 809

Get timestamp from X milliseconds ago in c++

I'm trying to get the linux timestamp from X milliseconds ago.

I know you can do something like this for seconds:

time_t old_time = difftime(time(nullptr), num_seconds)

However, I'm trying to get the timestamp (aka time from beginning of epoch) in milliseconds, and unfortunately it seems that difftime/time(nullptr) only works in increments of seconds.

I also saw some ideas around using std::chrono::system_clock but I wasn't able to get that to work, something around the way I was casting/etc. is wrong I think. Here is an example of what I tried (my very first step, doesn't even compile):

Clock::time_point time = Clock::now();
std::chrono::system_clock::duration diff = 
  std::chrono::duration<int,std::milli>(100);
time = time - diff;

time_t final_timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(time.time_since_epoch()).count();

Does anyone know of an easy solution for this issue? Thanks in advance!

Upvotes: 1

Views: 201

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218700

#include <chrono>
#include <iostream>

int
main()
{
    using namespace std::chrono;
    auto old_time = time_point_cast<milliseconds>(system_clock::now()) - 100ms;
    std::cout << old_time.time_since_epoch().count() << "ms\n";
}

This gets the current time UTC, truncates it to milliseconds precision, and then subtracts 100ms from that time point.

It then extracts the underlying value and prints it out (milliseconds since 1970-01-01 00:00:00.000 UTC).

Upvotes: 3

Nicholas Schroeder
Nicholas Schroeder

Reputation: 86

This should help out

#include <iostream>
#include <time.h>

using namespace std;

int main(int argc,char** argv){
    clock_t start_time = clock();

    const long int REPEAT_CYCLES = 500000000;
    int result = 0;

    for(long int i=0;i<REPEAT_CYCLES;i++)
        result = (result > 1000) ? result-1 : result+1; 

    clock_t finish_time = clock();

    cout << "WORK EXECUTION TIME: " << (double)(finish_time - start_time)/1000 << "ms" << endl;

    return EXIT_SUCCESS;
}

Upvotes: 0

Related Questions