Using only ANSI C, is there any way to measure time with milliseconds precision or more? I was browsing time.h but I only found second precision functions.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
The accepted answer is good enough.But my solution is more simple.I just test in Linux, use gcc (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0.
Alse use
gettimeofday
, thetv_sec
is the part of second, and thetv_usec
is microseconds, not milliseconds.It print:
1522139691342 1522139692342
, exactly a second.There is no ANSI C function that provides better than 1 second time resolution but the POSIX function
gettimeofday
provides microsecond resolution. The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.You can use this function like this:
This returns
Time elapsed: 1.000870
on my machine.I always use the clock_gettime() function, returning time from the CLOCK_MONOTONIC clock. The time returned is the amount of time, in seconds and nanoseconds, since some unspecified point in the past, such as system startup of the epoch.
The best precision you can possibly get is through the use of the x86-only "rdtsc" instruction, which can provide clock-level resolution (ne must of course take into account the cost of the rdtsc call itself, which can be measured easily on application startup).
The main catch here is measuring the number of clocks per second, which shouldn't be too hard.
timespec_get
from C11Returns up to nanoseconds, rounded to the resolution of the implementation.
Looks like an ANSI ripoff from POSIX'
clock_gettime
.Example: a
printf
is done every 100ms on Ubuntu 15.10:The C11 N1570 standard draft 7.27.2.5 "The timespec_get function says":
C++11 also got
std::chrono::high_resolution_clock
: C++ Cross-Platform High-Resolution Timerglibc 2.21 implementation
Can be found under
sysdeps/posix/timespec_get.c
as:so clearly:
only
TIME_UTC
is currently supportedit forwards to
__clock_gettime (CLOCK_REALTIME, ts)
, which is a POSIX API: http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.htmlLinux x86-64 has a
clock_gettime
system call.Note that this is not a fail-proof micro-benchmarking method because:
man clock_gettime
says that this measure may have discontinuities if you change some system time setting while your program runs. This should be a rare event of course, and you might be able to ignore it.this measures wall time, so if the scheduler decides to forget about your task, it will appear to run for longer.
For those reasons
getrusage()
might be a better better POSIX benchmarking tool, despite it's lower microsecond maximum precision.More information at: Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?