Android环境下高精度计时方案

android手机中有一个时钟计数寄存器,正常情况下,用户态程序是无法访问的,为了能够
访问这个寄存器,要写一个内核模块,加载到系统中。手机必须先root。

首先是内核模块的编译(开发环境为Ubuntu kylin 14.0.4):

几点修正的地方:
1. 国内android.googlesource.com可能无法连接,可以通过修改Hosts文件的方法进行连接。
    推荐地址:http://www.360kb.com/kb/2_122.html (反选)

2. 编译内核时,请确定环境变量是否设置正确,不然会报错。

然后是编写内核文件,代码如下:
#include <linux/module.h>
#include <linux/kernel.h>

int init_module()
{
   // 开启用户态访问时钟计数寄存器的功能
   asm volatile("mcr p15, 0, %0, c9, c14, 0" :: "r"(1));
   return 0;	
}

void cleanup_module()
{
   //关闭用户态访问时钟计数寄存器的功能
   asm volatile("mcr p15, 0, %0, c9, c14, 0" :: "r"(1));
}

最后提供可选的用户态代码,可以通过自己的需求去改:
 static inline unsigned int get_cyclecount (void)
 {
     unsigned int value;
      // Read CCNT Register
     asm volatile ("MRC p15, 0, %0, c9, c13, 0\t\n": "=r"(value));
      return value;
 }
 static inline void init_perfcounters (int32_t do_reset, int32_t enable_divider)
 {
    // in general enable all counters (including cycle counter)
    int32_t value = 1;

    // peform reset:
    if (do_reset)
   {
      value |= 2;     // reset all counters to zero.
      value |= 4;     // reset cycle counter to zero.
    }

   if (enable_divider)
      value |= 8;     // enable "by 64" divider for CCNT.

    value |= 16;

    // program the performance-counter control-register:
    asm volatile ("MCR p15, 0, %0, c9, c12, 0\t\n" :: "r"(value));

    // enable all counters:
    asm volatile ("MCR p15, 0, %0, c9, c12, 1\t\n" :: "r"(0x8000000f));

   // clear overflows:
    asm volatile ("MCR p15, 0, %0, c9, c12, 3\t\n" :: "r"(0x8000000f));
 }

   int time(){
      int i;
      int t[100];

    /* disable counter overflow interrupts (just in case)*/
      asm ("MCR p15, 0, %0, C9, C14, 2\n\t" :: "r"(0x8000000f));

      init_perfcounters (1, 0);
      unsigned int overhead = get_cyclecount();
      overhead = get_cyclecount() - overhead;
 // the beginning of the timing
       unsigned int t = get_cyclecount();
       for (i=0;i<100;i++)
       t[i]=i;
// the end of the timing
       t = get_cyclecount()- t;
   return ntime(t - overhead);
 }





展开阅读全文

没有更多推荐了,返回首页