c++ get milliseconds since some date

12,904

Solution 1

See std::clock()    

Solution 2

clock has been suggested a number of times. This has two problems. First of all, it often doesn't have a resolution even close to a millisecond (10-20 ms is probably more common). Second, some implementations of it (e.g., Unix and similar) return CPU time, while others (E.g., Windows) return wall time.

You haven't really said whether you want wall time or CPU time, which makes it hard to give a really good answer. On Windows, you could use GetProcessTimes. That will give you the kernel and user CPU times directly. It will also tell you when the process was created, so if you want milliseconds of wall time since process creation, you can subtract the process creation time from the current time (GetSystemTime). QueryPerformanceCounter has also been mentioned. This has a few oddities of its own -- for example, in some implementations it retrieves time from the CPUs cycle counter, so its frequency varies when/if the CPU speed changes. Other implementations read from the motherboard's 1.024 MHz timer, which does not vary with the CPU speed (and the conditions under which each are used aren't entirely obvious).

On Unix, you can use GetTimeOfDay to just get the wall time with (at least the possibility of) relatively high precision. If you want time for a process, you can use times or getrusage (the latter is newer and gives more complete information that may also be more precise).

Bottom line: as I said in my comment, there's no way to get what you want portably. Since you haven't said whether you want CPU time or wall time, even for a specific system, there's not one right answer. The one you've "accepted" (clock()) has the virtue of being available on essentially any system, but what it returns also varies just about the most widely.

Solution 3

Include time.h, and then use the clock() function. It returns the number of clock ticks elapsed since the program was launched. Just divide it by "CLOCKS_PER_SEC" to obtain the number of seconds, you can then multiply by 1000 to obtain the number of milliseconds.

Solution 4

Some cross platform solution. This code was used for some kind of benchmarking:

#ifdef WIN32
  LARGE_INTEGER g_llFrequency = {0};
  BOOL g_bQueryResult = QueryPerformanceFrequency(&g_llFrequency);
#endif

//...

long long osQueryPerfomance()
{
#ifdef WIN32
  LARGE_INTEGER llPerf = {0};
  QueryPerformanceCounter(&llPerf);
  return llPerf.QuadPart * 1000ll / ( g_llFrequency.QuadPart / 1000ll);
#else
  struct timeval stTimeVal;
  gettimeofday(&stTimeVal, NULL);
  return stTimeVal.tv_sec * 1000000ll + stTimeVal.tv_usec;
#endif
}

Solution 5

The most portable way is using the clock function.It usually reports the time that your program has been using the processor, or an approximation thereof. Note however the following:

  • The resolution is not very good for GNU systems. That's really a pity.

  • Take care of casting everything to double before doing divisions and assignations.

  • The counter is held as a 32 bit number in GNU 32 bits, which can be pretty annoying for long-running programs.

There are alternatives using "wall time" which give better resolution, both in Windows and Linux. But as the libc manual states: If you're trying to optimize your program or measure its efficiency, it's very useful to know how much processor time it uses. For that, calendar time and elapsed times are useless because a process may spend time waiting for I/O or for other processes to use the CPU.

Share:
12,904
JnBrymn
Author by

JnBrymn

@JnBrymn Author of Taming Search manning.com/turnbull/ I'm all about search relevance.

Updated on July 09, 2022

Comments

  • JnBrymn
    JnBrymn almost 2 years

    I need some way in c++ to keep track of the number of milliseconds since program execution. And I need the precision to be in milliseconds. (In my googling, I've found lots of folks that said to include time.h and then multiply the output of time() by 1000 ... this won't work.)

  • corsiKa
    corsiKa almost 14 years
    I love the sample program in that link, especially the while loop.
  • jim mcnamara
    jim mcnamara almost 14 years
    CLOCKS_PER_SEC is not guaranteed to be in milliseconds.
  • Stephen
    Stephen almost 14 years
    Surely you mean multiply by 1000?
  • anijhaw
    anijhaw almost 14 years
    the Question said he needs precision not the divide by 1000 solutions :)
  • cpx
    cpx almost 14 years
    Yes, It would be OS dependent.
  • Stephen
    Stephen almost 14 years
    Also, surely you mean divide by CLOCKS_PER_SECOND? Or are my maths skills failing me? (My in-head example was: "I run 10m/s. I have run for 2 metres. Therefore, it has taken 0.2s").
  • Randolpho
    Randolpho almost 14 years
    @jim mcnamara: it's supposed to guarantee to expand into the number of clock cycles per second. So it might not be in milliseconds, but it'll get you seconds, and it shouldn't be too hard to get milliseconds from that...
  • loentar
    loentar almost 14 years
    gettimeofday() is not supported on windows. While compiling code in windows QueryPerformanceCounter will be used. Is't a high resolution timer. This method is very fast and precise.
  • Stephen
    Stephen almost 14 years
    I think what Jim means is that it will be in round seconds - which it won't necessarily be. If there are (random numbers picked out of the air) 15,000 clocks a second, and your program has taken 45 clocks, you will take 45, divide it by 15000 and get 0.003 seconds. You then multiply by 1000 to get 3 milliseconds. Done. Unless I've failed maths. Which is possible.
  • deft_code
    deft_code almost 14 years
    He wants a time delta which is neither wall time nor cpu time.
  • deft_code
    deft_code almost 14 years
    -1 clock only counts time while you're program is active. Any blocking calls are not counted ( filesystem access, networking, sleep, etc).
  • Admin
    Admin almost 14 years
    This is not a good solution.. clock is good but it will have problems for future use as others have said
  • Admin
    Admin almost 14 years
    What he really needs to do is just simply record the time when his program starts and when he needs to know how long it has been running, just get the current time again and subtract the two values. That will be about as precise as you can get.
  • Jerry Coffin
    Jerry Coffin almost 14 years
    @Caspin: First, I question whether his question is sufficiently clear to say it's a delta with any certainty. Second, even if it is a delta, it still has to be a delta of wall or CPU time (i.e., "How long since process started?", or "how much CPU time has the process used?"
  • RnMss
    RnMss over 10 years
    clock() is not real-time clock. It is the CPU-time clock, which may run faster when multi-threading is used, and slower (stopped) when blocked by some IO.
  • RnMss
    RnMss over 10 years
    Oh my god, this is Windows only!