Linux time in milliseconds

How to get the current time in milliseconds from C in Linux?

How do I get the current time on Linux in milliseconds?

7 Answers 7

This can be achieved using the POSIX clock_gettime function.

In the current version of POSIX, gettimeofday is marked obsolete. This means it may be removed from a future version of the specification. Application writers are encouraged to use the clock_gettime function instead of gettimeofday .

Here is an example of how to use clock_gettime :

If your goal is to measure elapsed time, and your system supports the «monotonic clock» option, then you should consider using CLOCK_MONOTONIC instead of CLOCK_REALTIME .

You have to do something like this:

Following is the util function to get current timestamp in milliseconds:

About timezone:

gettimeofday() support to specify timezone, I use NULL, which ignore the timezone, but you can specify a timezone, if need.

@Update — timezone

Since the long representation of time is not relevant to or effected by timezone itself, so setting tz param of gettimeofday() is not necessary, since it won’t make any difference.

And, according to man page of gettimeofday() , the use of the timezone structure is obsolete, thus the tz argument should normally be specified as NULL, for details please check the man page.

Источник

Set linux time to millisecond precision

I have an embedded Linux device that interfaces with another «master» device over a serial comm protocol. Periodically the master passes its date down to the slave device, because later the slave will return information to the master that needs to be accurately timestamped. However, the Linux ‘date’ command only sets the system date to within a second accuracy. This isn’t enough for our uses.

Does anybody know how to set a Linux machine’s time more precisely than 1 second?

4 Answers 4

The settimeofday(2) method given in other answers has a serious problem: it does exactly what you say you want. 🙂

The problem with directly changing a system’s time, instantaneously, is that it can confuse programs that get the time of day before and after the change if the adjustment was negative. That is, they can perceive time to go backwards.

The fix for this is adjtime(3) which is simple and portable, or adjtimex(2) which is complicated, powerful and Linux-specific. Both of these calls use sophisticated algorithms to slowly adjust the system time over some period, forward only, until the desired change is achieved.

Читайте также:  Configure opencv in windows

By the way, are you sure you aren’t reinventing the wheel here? I recommend that you read Julien Ridoux and Darryl Veitch’s ACM Queue paper Principles of Robust Timing over the Internet. You’re working on embedded systems, so I would expect the ringing in Figure 5 to give you cold shivers. Can you say «damped oscillator?» adjtime() and adjtimex() use this troubled algorithm, so in some sense I am arguing against my own advice above, but the Mills algorithm is still better than the step adjustment non-algorithm. If you choose to implement RADclock instead, so much the better.

Источник

C++ — How can we get a millisecond timestamp in linux?

How to convert std::chrono::monotonic_clock::now() to milliseconds and cast it to long?

using steady_clock or high_resolution_clock from chrono is also same. I have seen into std::chrono::duration_cast but I only want the current timestamp and not any duration gaps.

2 Answers 2

The current timestamp is defined with respect to some point in time (hence it is a duration). For instance, it is «typical» to get a timestamp with respect to the beginning of the Epoch (January 1st 1970, in Unix). You can do that by using time_since_epoch() :

To get the value in milliseconds you would need to cast it to std::chrono::milliseconds , instead.

All the built-in clocks have an associated «epoch» which is their base time. The actual date/time of the epoch is not specified, and may vary from clock to clock.

If you just want a number for comparisons then some-clock ::now().time_since_epoch() will give you a duration for the time since the epoch for that clock, which you can convert to an integer with the count() member of the duration type. The units of this will depend on the period of the clock. If you want specific units then use duration_cast first:

As I said, this is only good for comparisons, not as an absolute time stamp, since the epoch is unspecified.

If you need a UNIX timestamp then you need to use std::chrono::system_clock , which has a to_time_t() function for converting a time_point to a time_t .

Alternatively, you can take a baseline count at a particular point in your program, along with the corresponding time from gettimeofday or something, and then use that to convert relative counts to absolute times.

Источник

Command to get time in milliseconds

Is there a shell command in Linux to get the time in milliseconds?

14 Answers 14

date +»%T.%N» returns the current time with nanoseconds.

date +»%T.%6N» returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds.

date +»%T.%3N» returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.

In general, every field of the date command’s format can be given an optional field width.

date +%s%N returns the number of seconds + current nanoseconds.

Читайте также:  Fbreader для windows что это

Therefore, echo $(($(date +%s%N)/1000000)) is what you need.

date +%s returns the number of seconds since the epoch, if that’s useful.

Nano is 10 −9 and milli 10 −3 . Hence, we can use the three first characters of nanoseconds to get the milliseconds:

%N nanoseconds (000000000..999999999)

%s seconds since 1970-01-01 00:00:00 UTC

On OS X, where date does not support the %N flag, I recommend installing coreutils using Homebrew. This will give you access to a command called gdate that will behave as date does on Linux systems.

For a more «native» experience, you can always add this to your .bash_aliases :

Here is a somehow portable hack for Linux for getting time in milliseconds:

This is a very cheap operation, which works with shell internals and procfs.

date command didnt provide milli seconds on OS X, so used an alias from python

EDIT: following the comment from @CharlesDuffy. Forking any child process takes extra time.

Python is still improving it’s VM start time, and it is not as fast as ahead-of-time compiled code (such as date ).

On my machine, it took about 30ms — 60ms (that is 5x-10x of 6ms taken by date )

I figured awk is lightweight than python , so awk takes in the range of 6ms to 12ms (i.e. 1x to 2x of date):

The other answers are probably sufficient in most cases but I thought I’d add my two cents as I ran into a problem on a BusyBox system.

The system in question did not support the %N format option and doesn’t have no Python or Perl interpreter.

After much head scratching, we (thanks Dave!) came up with this:

It extracts the seconds and microseconds from the output of adjtimex (normally used to set options for the system clock) and prints them without new lines (so they get glued together). Note that the microseconds field has to be pre-padded with zeros, but this doesn’t affect the seconds field which is longer than six digits anyway. From this it should be trivial to convert microseconds to milliseconds.

If you need a trailing new line (maybe because it looks better) then try

Also note that this requires adjtimex and awk to be available. If not then with BusyBox you can point to them locally with:

And then call the above as

Or of course you could put them in your PATH

The above worked on my BusyBox device. On Ubuntu I tried the same thing and realised that adjtimex has different versions. On Ubuntu this worked to output the time in seconds with decimal places to microseconds (including a trailing new line)

I wouldn’t do this on Ubuntu though. I would use date +%s%N

Читайте также:  Шрифт verdana для linux

Источник

C++ obtaining milliseconds time on Linux — clock() doesn’t seem to work properly

On Windows, clock() returns the time in milliseconds, but on this Linux box I’m working on, it rounds it to the nearest 1000 so the precision is only to the «second» level and not to the milliseconds level.

I found a solution with Qt using the QTime class, instantiating an object and calling start() on it then calling elapsed() to get the number of milliseconds elapsed.

I got kind of lucky because I’m working with Qt to begin with, but I’d like a solution that doesn’t rely on third party libraries,

Is there no standard way to do this?

UPDATE

Please don’t recommend Boost ..

If Boost and Qt can do it, surely it’s not magic, there must be something standard that they’re using!

16 Answers 16

Please note that clock does not measure wall clock time. That means if your program takes 5 seconds, clock will not measure 5 seconds necessarily, but could more (your program could run multiple threads and so could consume more CPU than real time) or less. It measures an approximation of CPU time used. To see the difference consider this code

It outputs on my system

Because all we did was sleeping and not using any CPU time! However, using gettimeofday we get what we want (?)

Outputs on my system

If you need more precision but want to get CPU time, then you can consider using the getrusage function.

You could use gettimeofday at the start and end of your method and then difference the two return structs. You’ll get a structure like the following:

EDIT: As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have it available, which should be almost everywhere these days.

EDIT: Someone else commented that you can also use modern C++ with std::chrono::high_resolution_clock, but that isn’t guaranteed to be monotonic. Use steady_clock instead.

I also recommend the tools offered by Boost. Either the mentioned Boost Timer, or hack something out of Boost.DateTime or there is new proposed library in the sandbox — Boost.Chrono: This last one will be a replacement for the Timer and will feature:

  • The C++0x Standard Library’s time utilities, including:
    • Class template duration
    • Class template time_point
    • Clocks:
      • system_clock
      • monotonic_clock
      • high_resolution_clock
  • Class template timer , with typedefs:
    • system_timer
    • monotonic_timer
    • high_resolution_timer
  • Process clocks and timers:
    • process_clock , capturing real, user-CPU, and system-CPU times.
    • process_timer , capturing elapsed real, user-CPU, and system-CPU times.
    • run_timer , convenient reporting of |process_timer| results.
  • The C++0x Standard Library’s compile-time rational arithmetic.

Here is the source of the feature list

I’ve written a Timer class based on CTT’s answer. It can be used in the following way:

Источник

Оцените статью