7

In Java you can do this:

long now = (new Date()).getTime();

How can I do the same but in C++?

Pharap
  • 3,161
  • 4
  • 31
  • 44
atomsfat
  • 2,693
  • 6
  • 30
  • 34
  • Check this thread (it's nanoseconds, but I guess it could be converted to milliseconds as well) http://stackoverflow.com/questions/275004/c-timer-function-to-provide-time-in-nano-seconds – Default May 14 '10 at 06:52
  • 9
    In Java you should use `System.currentTimeMillis()`. – Steffen Heil Aug 30 '13 at 14:19

7 Answers7

12

Because C++0x is awesome

namespace sc = std::chrono;

auto time = sc::system_clock::now(); // get the current time

auto since_epoch = time.time_since_epoch(); // get the duration since epoch

// I don't know what system_clock returns
// I think it's uint64_t nanoseconds since epoch
// Either way this duration_cast will do the right thing
auto millis = sc::duration_cast<sc::milliseconds>(since_epoch);

long now = millis.count(); // just like java (new Date()).getTime();

This works with gcc 4.4+. Compile it with --std=c++0x. I don't know if VS2010 implements std::chrono yet.

deft_code
  • 51,579
  • 27
  • 135
  • 215
9

There is no such method in standard C++ (in standard C++, there is only second-accuracy, not millisecond). You can do it in non-portable ways, but since you didn't specify I will assume that you want a portable solution. Your best bet, I would say, is the boost function microsec_clock::local_time().

Dean Harding
  • 67,567
  • 11
  • 132
  • 174
6

I like to have a function called time_ms defined as such:

// Used to measure intervals and absolute times
typedef int64_t msec_t;

// Get current time in milliseconds from the Epoch (Unix)
// or the time the system started (Windows).
msec_t time_ms(void);

The implementation below should work in Windows as well as Unix-like systems.

#if defined(__WIN32__)

#include <windows.h>

msec_t time_ms(void)
{
    return timeGetTime();
}

#else

#include <sys/time.h>

msec_t time_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (msec_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

#endif

Note that the time returned by the Windows branch is milliseconds since the system started, while the time returned by the Unix branch is milliseconds since 1970. Thus, if you use this code, only rely on differences between times, not the absolute time itself.

Joey Adams
  • 37,814
  • 17
  • 79
  • 110
  • 1
    timeGetTime returns the time since Windows was started, not the milliseconds since the Epoch. – Matthew Flaschen May 14 '10 at 04:49
  • 1
    You could use a bit of math and `GetSystemTimeAsFileTime` on Windows (http://msdn.microsoft.com/en-us/library/ms724397%28v=VS.85%29.aspx). Personally, I like `microsec_clock::local_time()` - all the hard work's been done already :-) – Dean Harding May 14 '10 at 04:57
  • Can you change the comment above the `time_ms` prototype too? – Matthew Flaschen May 14 '10 at 05:04
4

You can try this code (get from StockFish chess engine source code (GPL)):

#include <iostream>
#include <stdio>

#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix
    #  include <sys/time.h>
    typedef timeval sys_time_t;
    inline void system_time(sys_time_t* t) {
        gettimeofday(t, NULL);
    }
    inline long long time_to_msec(const sys_time_t& t) {
        return t.tv_sec * 1000LL + t.tv_usec / 1000;
    }
    #else // Windows and MinGW
    #  include <sys/timeb.h>
    typedef _timeb sys_time_t;
    inline void system_time(sys_time_t* t) { _ftime(t); }
    inline long long time_to_msec(const sys_time_t& t) {
        return t.time * 1000LL + t.millitm;
    }
#endif


int main() {
    sys_time_t t;
    system_time(&t);
    long long currentTimeMs = time_to_msec(t);
    std::cout << "currentTimeMs:" << currentTimeMs << std::endl;
    getchar();  // wait for keyboard input
}
TrungTN
  • 2,172
  • 1
  • 12
  • 4
3

Standard C++ does not have a time function with subsecond precision.

However, almost every operating system does. So you have to write code that is OS-dependent.

Win32:
  GetSystemTime()
  GetSystemTimeAsFileTime()

Unix/POSIX:
  gettimeofday()
  clock_gettime()

David R Tribble
  • 10,646
  • 4
  • 39
  • 50
0

Boost has a useful library for doing this:

http://www.boost.org/doc/libs/1_43_0/doc/html/date_time.html

ptime microsec_clock::local_time() or ptime second_clock::local_time()

JH.
  • 3,717
  • 2
  • 17
  • 19
-2

Java:

package com.company;

public class Main {

    public static void main(String[] args) {
        System.out.println(System.currentTimeMillis());

    }
}

c++:

#include <stdio.h>
#include <windows.h>

__int64 currentTimeMillis() {
    FILETIME f;
    GetSystemTimeAsFileTime(&f);
    (long long)f.dwHighDateTime;
    __int64 nano = ((__int64)f.dwHighDateTime << 32LL) + (__int64)f.dwLowDateTime;
    return (nano - 116444736000000000LL) / 10000;
}

int main() {
    printf("%lli\n ", currentTimeMillis());

    return 0;
}
ilw
  • 2,192
  • 4
  • 25
  • 50