本文實(shí)例講述了Android編程計(jì)算函數(shù)時(shí)間戳的相關(guān)方法。分享給大家供大家參考,具體如下:
對(duì)于做性能的人來(lái)說(shuō),知道時(shí)間的花在哪了是比較重要的,可以在函數(shù)前后得到系統(tǒng)的時(shí)間,計(jì)算時(shí)間戳能夠得到每個(gè)函數(shù)的時(shí)間。
在JAVA中可以通過(guò)System.currentTimeMillis()得到:
long start_time = System.currentTimeMillis();View.draw(canvas);long end_time = System.currentTimeMillis();long spend_time = end_time - start_time;Log.i(TAG,"mView.draw: spend_time = " + spend_time);
在native的代碼中,可以通過(guò)下面的方式得到函數(shù)的執(zhí)行時(shí)間:
#include <stdio.h>#include <sys/time.h>void main (){ struct timeval time; gettimeofday(&time, NULL); printf ( "/007The current date/time is: %lld/n", time.tv_sec * 1000 + time.tv_usec /1000);}在kernel里面,可以通過(guò)rtc,跟上層應(yīng)用的時(shí)間對(duì)應(yīng)起來(lái),如下面的例子:
#include <linux/time.h>#include <linux/rtc.h>struct timespec time_start, time_end;struct rtc_time tm_start, tm_end;long time_nsec = 0;getnstimeofday(&time_start);rtc_time_to_tm(time_end.tv_sec, &tm_start);printk(KERN_ERR "/n (%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)/n",tm_start.tm_year + 1900, tm_start.tm_mon + 1, tm_start.tm_mday,tm_start.tm_hour, tm_start.tm_min, tm_start.tm_sec, time_start.tv_nsec);.......getnstimeofday(&time_end);rtc_time_to_tm(time_end.tv_sec, &tm_end);time_nsec = time_end.tv_nsec - time_start.tv_nsec;printk(KERN_ERR "/n tid: %d, common: %s /n", current->pid, current->comm);printk(KERN_ERR "/n end(%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)/n",tm_end.tm_year + 1900, tm_end.tm_mon + 1, tm_end.tm_mday,tm_end.tm_hour, tm_end.tm_min, tm_end.tm_sec, time_end.tv_nsec);printk(KERN_ERR "/n mdss_fb_commit_wq_handler end, time_nsec : %ld /n" , time_nsec);
當(dāng)然過(guò)從java到native到kernel一個(gè)流程跟下去,有可能會(huì)發(fā)現(xiàn)user space里面的耗時(shí)比較多,而kernel里面卻沒(méi)有耗時(shí)的情況,這是因?yàn)橛羞M(jìn)程調(diào)度的存在。最近就遇到了這樣的問(wèn)題,user space一個(gè)函數(shù)耗時(shí)30ms,但是在kernel里面卻沒(méi)有花時(shí)間,因?yàn)閺膋ernel返回到user space的時(shí)候,進(jìn)行了進(jìn)程調(diào)度,而此時(shí)的user space的thread block了,才會(huì)產(chǎn)生這樣的情況,希望注意。
Java得到當(dāng)前的年月日,時(shí)分秒格式的時(shí)間
import java.text.SimpleDateFormat;SimpleDateFormat mFormat = new java.text.SimpleDateFormat("yyyy:MM:dd HH:mm:ss:SSS");String time = mFormat.format(System.currentTimeMillis());Native得到當(dāng)前的年月日,時(shí)分秒格式的時(shí)間
timeval tv;gettimeofday(&tv, NULL);int milli = tv.tv_usec / 1000;char buffer [80];strftime(buffer, 80, "%Y:%m:%d %H:%M:%S", localtime(&tv.tv_sec));char currentTime[84] = "";sprintf(currentTime, "%s.%d", buffer, milli);ALOGD("time: %s /n", currentTime);到現(xiàn)今為止,終于把Android Java、Native、Kernel的時(shí)間時(shí)間對(duì)應(yīng)起來(lái)了,對(duì)做系統(tǒng)性能的人來(lái)說(shuō),這是多么重要的事情呀!
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
|
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注