clock.h revision 13082f80dcee5f119cdb68a4dbc972cd2b939668
1/*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ANDROID_AUDIO_CLOCK_H
18#define ANDROID_AUDIO_CLOCK_H
19
20#include <time.h>
21
22/**
23 * \brief Converts time in ns to a time string, with format similar to logcat.
24 * \param ns          input time in nanoseconds to convert.
25 * \param buffer      caller allocated string buffer, buffer_length must be >= 19 chars
26 *                    in order to fully fit in time.  The string is always returned
27 *                    null terminated if buffer_size is greater than zero.
28 * \param buffer_size size of buffer.
29 */
30static inline void audio_utils_ns_to_string(int64_t ns, char *buffer, int buffer_size)
31{
32    const int one_second = 1000000000;
33    const time_t sec = ns / one_second;
34    struct tm tm;
35    localtime_r(&sec, &tm);
36    if (snprintf(buffer, buffer_size, "%02d-%02d %02d:%02d:%02d.%03d",
37        tm.tm_mon + 1, // localtime_r uses months in 0 - 11 range
38        tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
39        (int)(ns % one_second / 1000000)) < 0) {
40        buffer[0] = '\0'; // null terminate on format error, which should not happen
41    }
42}
43
44/**
45 * \brief Converts a timespec to nanoseconds.
46 * \param ts   input timespec to convert.
47 * \return     timespec converted to nanoseconds.
48 */
49static inline int64_t audio_utils_ns_from_timespec(const struct timespec *ts)
50{
51    return ts->tv_sec * 1000000000LL + ts->tv_nsec;
52}
53
54/**
55 * \brief Gets the real time clock in nanoseconds.
56 * \return the real time clock in nanoseconds, or 0 on error.
57 */
58static inline int64_t audio_utils_get_real_time_ns() {
59    struct timespec now_ts;
60    if (clock_gettime(CLOCK_REALTIME, &now_ts) == 0) {
61        return audio_utils_ns_from_timespec(&now_ts);
62    }
63    return 0; // should not happen.
64}
65
66#endif  // !ANDROID_AUDIO_CLOCK_H
67