jni_android_unittest.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/android/jni_android.h"
  5. #include "base/at_exit.h"
  6. #include "base/logging.h"
  7. #include "base/time/time.h"
  8. #include "testing/gtest/include/gtest/gtest.h"
  9. namespace base {
  10. namespace android {
  11. namespace {
  12. std::atomic<jmethodID> g_atomic_id(nullptr);
  13. int LazyMethodIDCall(JNIEnv* env, jclass clazz, int p) {
  14. jmethodID id = base::android::MethodID::LazyGet<
  15. base::android::MethodID::TYPE_STATIC>(
  16. env, clazz,
  17. "abs",
  18. "(I)I",
  19. &g_atomic_id);
  20. return env->CallStaticIntMethod(clazz, id, p);
  21. }
  22. int MethodIDCall(JNIEnv* env, jclass clazz, jmethodID id, int p) {
  23. return env->CallStaticIntMethod(clazz, id, p);
  24. }
  25. } // namespace
  26. TEST(JNIAndroidMicrobenchmark, MethodId) {
  27. JNIEnv* env = AttachCurrentThread();
  28. ScopedJavaLocalRef<jclass> clazz(GetClass(env, "java/lang/Math"));
  29. base::Time start_lazy = base::Time::Now();
  30. int o = 0;
  31. for (int i = 0; i < 1024; ++i)
  32. o += LazyMethodIDCall(env, clazz.obj(), i);
  33. base::Time end_lazy = base::Time::Now();
  34. jmethodID id = g_atomic_id;
  35. base::Time start = base::Time::Now();
  36. for (int i = 0; i < 1024; ++i)
  37. o += MethodIDCall(env, clazz.obj(), id, i);
  38. base::Time end = base::Time::Now();
  39. // On a Galaxy Nexus, results were in the range of:
  40. // JNI LazyMethodIDCall (us) 1984
  41. // JNI MethodIDCall (us) 1861
  42. LOG(ERROR) << "JNI LazyMethodIDCall (us) " <<
  43. base::TimeDelta(end_lazy - start_lazy).InMicroseconds();
  44. LOG(ERROR) << "JNI MethodIDCall (us) " <<
  45. base::TimeDelta(end - start).InMicroseconds();
  46. LOG(ERROR) << "JNI " << o;
  47. }
  48. } // namespace android
  49. } // namespace base