Skip to content

Commit 2803dac

Browse files
committed
posix: Add posix CLOCK_THREAD_CPUTIME_ID support
Add posix 'CLOCK_THREAD_CPUTIME_ID' support to measure the total CPU execution time of the current thread. Signed-off-by: James Roy <rruuaanng@outlook.com>
1 parent 961593d commit 2803dac

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

lib/posix/options/Kconfig.timer

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ if POSIX_TIMERS
1717

1818
config POSIX_THREAD_CPUTIME
1919
bool "POSIX per-thread CPU-time clocks"
20+
select THREAD_RUNTIME_STATS
21+
select SCHED_THREAD_USAGE_ANALYSIS
2022
help
2123
This enables CLOCK_THREAD_CPUTIME_ID.
2224

lib/posix/options/clock.c

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,23 @@ int z_impl___posix_clock_get_base(clockid_t clock_id, struct timespec *base)
4343
*base = rt_clock_base;
4444
}
4545
break;
46+
#ifdef CONFIG_POSIX_THREAD_CPUTIME
47+
case CLOCK_THREAD_CPUTIME_ID: {
48+
uint64_t ns;
49+
k_thread_runtime_stats_t stats;
50+
k_tid_t thread = k_current_get();
51+
52+
if (!k_thread_runtime_stats_is_enabled(thread)) {
53+
errno = EINVAL;
54+
return -1;
55+
}
56+
k_thread_runtime_stats_get(thread, &stats);
57+
ns = k_cyc_to_ns_floor64(stats.execution_cycles);
58+
base->tv_sec = ns / NSEC_PER_SEC;
59+
base->tv_nsec = ns % NSEC_PER_SEC;
60+
break;
61+
}
62+
#endif /* CONFIG_POSIX_THREAD_CPUTIME */
4663

4764
default:
4865
errno = EINVAL;
@@ -75,6 +92,13 @@ int clock_gettime(clockid_t clock_id, struct timespec *ts)
7592
(void)__posix_clock_get_base(clock_id, &base);
7693
break;
7794

95+
#ifdef CONFIG_POSIX_THREAD_CPUTIME
96+
case CLOCK_THREAD_CPUTIME_ID:
97+
(void)__posix_clock_get_base(clock_id, &base);
98+
*ts = base;
99+
return 0;
100+
#endif /* CONFIG_POSIX_THREAD_CPUTIME */
101+
78102
default:
79103
errno = EINVAL;
80104
return -1;

0 commit comments

Comments
 (0)