am 4ef0e59f: Merge "Reimplement clock(3) using clock_gettime(3)"

* commit '4ef0e59f339ad138eabe3bc408beda6004f5ea83':
  Reimplement clock(3) using clock_gettime(3)
This commit is contained in:
Elliott Hughes 2014-10-04 02:17:19 +00:00 committed by Android Git Automerger
commit 5f86872e67
2 changed files with 15 additions and 6 deletions

View File

@ -30,12 +30,13 @@
#include <sys/sysconf.h> #include <sys/sysconf.h>
#include <sys/times.h> #include <sys/times.h>
#include "private/bionic_constants.h"
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock.html // http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock.html
clock_t clock() { clock_t clock() {
tms t; timespec ts;
times(&t); if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == -1) {
// Although times(2) and clock(3) both use the type clock_t, the units are return -1;
// different. For times(2) it's pure clock ticks, but for clock(3) the unit }
// is CLOCKS_PER_SEC, so we need to scale appropriately. return (ts.tv_sec * CLOCKS_PER_SEC) + (ts.tv_nsec / (NS_PER_S / CLOCKS_PER_SEC));
return (t.tms_utime + t.tms_stime) * (CLOCKS_PER_SEC / sysconf(_SC_CLK_TCK));
} }

View File

@ -404,3 +404,11 @@ TEST(time, clock_gettime) {
ASSERT_EQ(0, ts2.tv_sec); ASSERT_EQ(0, ts2.tv_sec);
ASSERT_LT(ts2.tv_nsec, 1000000); ASSERT_LT(ts2.tv_nsec, 1000000);
} }
TEST(time, clock) {
// clock(3) is hard to test, but a 1s sleep should cost less than 1ms.
clock_t t0 = clock();
sleep(1);
clock_t t1 = clock();
ASSERT_LT(t1 - t0, CLOCKS_PER_SEC / 1000);
}