1--[[ 2Copyright 2016 GitHub, Inc 3 4Licensed under the Apache License, Version 2.0 (the "License"); 5you may not use this file except in compliance with the License. 6You may obtain a copy of the License at 7 8http://www.apache.org/licenses/LICENSE-2.0 9 10Unless required by applicable law or agreed to in writing, software 11distributed under the License is distributed on an "AS IS" BASIS, 12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13See the License for the specific language governing permissions and 14limitations under the License. 15]] 16local ffi = require("ffi") 17 18-- Avoid duplicate declarations if syscall library is present 19local has_syscall, _ = pcall(require, "syscall") 20if not has_syscall then 21 ffi.cdef [[ 22 typedef int clockid_t; 23 typedef long time_t; 24 25 struct timespec { 26 time_t tv_sec; 27 long tv_nsec; 28 }; 29 30 int clock_gettime(clockid_t clk_id, struct timespec *tp); 31 int clock_nanosleep(clockid_t clock_id, int flags, 32 const struct timespec *request, struct timespec *remain); 33 ]] 34end 35ffi.cdef [[ 36int get_nprocs(void); 37uint64_t strtoull(const char *nptr, char **endptr, int base); 38]] 39 40local CLOCK = { 41 REALTIME = 0, 42 MONOTONIC = 1, 43 PROCESS_CPUTIME_ID = 2, 44 THREAD_CPUTIME_ID = 3, 45 MONOTONIC_RAW = 4, 46 REALTIME_COARSE = 5, 47 MONOTONIC_COARSE = 6, 48} 49 50local function time_ns(clock) 51 local ts = ffi.new("struct timespec[1]") 52 assert(ffi.C.clock_gettime(clock or CLOCK.MONOTONIC_RAW, ts) == 0, 53 "clock_gettime() failed: "..ffi.errno()) 54 return tonumber(ts[0].tv_sec * 1e9 + ts[0].tv_nsec) 55end 56 57local function sleep(seconds, clock) 58 local s, ns = math.modf(seconds) 59 local ts = ffi.new("struct timespec[1]") 60 61 ts[0].tv_sec = s 62 ts[0].tv_nsec = ns / 1e9 63 64 ffi.C.clock_nanosleep(clock or CLOCK.MONOTONIC, 0, ts, nil) 65end 66 67local function cpu_count() 68 return tonumber(ffi.C.get_nprocs()) 69end 70 71local function tonumber64(n, base) 72 assert(type(n) == "string") 73 return ffi.C.strtoull(n, nil, base or 10) 74end 75 76return { 77 time_ns=time_ns, 78 sleep=sleep, 79 CLOCK=CLOCK, 80 cpu_count=cpu_count, 81 tonumber64=tonumber64, 82} 83