最近项目开发,需要获取到当前时间并且精确到微秒。但是一查资料发现似乎只能精确到到毫秒级,通过
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String str = formatter.format(new Date());
或者
Calendar calendar = Calendar.getInstance();
long mm = calendar.get(Calendar.MILLISECOND);
最后几经周折,可以通过c代码得到得到当前时间的微秒值,于是便通过jni方式得到了时间的微秒值。
其中c代码:
JNIEXPORT jlongArray JNICALL Java_com_test_ndkhelloword_MainActivity_getTimesFromJni(
JNIEnv *env, jobject thiz) {
jlongArray time = env->NewLongArray(2);
jlong temp[] = { 0, 0 };
struct timeval begin;
gettimeofday(&begin, NULL);
temp[0] = begin.tv_sec;
temp[1] = begin.tv_usec;
env->SetLongArrayRegion(time, 0, 2, temp);
return time;
}
还好最后找到了办法,特此分享。