Update
After checking the time resolution, we tried to debug the problem in kernel space.
unsigned long long task_sched_runtime(struct task_struct *p)
{
unsigned long flags;
struct rq *rq;
u64 ns = 0;
rq = task_rq_lock(p, &flags);
ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
task_rq_unlock(rq, &flags);
//printk("task_sched runtime\n");
return ns;
}
Our new experiment shows that the time p->se.sum_exec_runtime
is not updated instantly. But if we add printk()
inside the function. the time will be updated instantly.
Old
We are developing an Android program.
However, the time measured by the function threadCpuTimenanos()
is not always correct on our platform.
After experimenting, we found that the time returned from clock_gettime
is not updated instantly.
Even after several while loop iterations, the time we get still doesn't change.
Here's our sample code:
while(1)
{
test = 1;
test = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
printf(" clock gettime test 1 %lx, %lx , ret = %d\n",now.tv_sec , now.tv_nsec,test );
pre = now.tv_nsec;
sleep(1);
}
This code runs okay on an x86 PC. But it does not run correctly in our embedded platform ARM Cortex-A9 with kernel 2.6.35.13.
Any ideas?
In the android CTS, there is a case that has the same problem. read timer twice but they are the same
testThreadCpuTimeNanos fail junit.framework.AssertionFailedError at android.os.cts.DebugTest.testThreadCpuTimeNanos
The
CLOCK_THREAD_CPUTIME_ID
clock measures CPU time spent, not realtime, and you're spending almost-zero CPU time. Also,CLOCK_THREAD_CPUTIME_ID
(the thread-specific CPU time) is implemented incorrectly on Linux/glibc and likely does not even work at all on glibc.CLOCK_PROCESS_CPUTIME_ID
or whatever that one's called should work better.I changed the clock_gettime to use the CLOCK_MONOTONIC_RAW , assigned the thread to one CPU and I get different values. I am also working with a dual cortex-A9
The resolution of
clock_gettime
is platform dependent. Useclock_getres()
to find the resolution on your platform. According to the results of your experiment, clock resolutions on pc-x86 and on your target platform are different.