Using the Android Native Development Kit (NDK)
Upcoming SlideShare
Loading in...5
×
 

Like this? Share it with your network

Share

Using the Android Native Development Kit (NDK)

on

  • 2,334 views

Learn how to use the Android NDK and integrate C/C++ code in your Android apps.

Learn how to use the Android NDK and integrate C/C++ code in your Android apps.

Statistics

Views

Total Views
2,334
Views on SlideShare
2,334
Embed Views
0

Actions

Likes
1
Downloads
45
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Using the Android Native Development Kit (NDK) Presentation Transcript

  • 1. Using the Android* Native Development Kit (NDK) Xavier Hallade, Technical Marketing Engineer @ph0b - ph0b.com
  • 2. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Summary and Q&A Break • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 3
  • 3. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Summary and Q&A Break • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 4
  • 4. Android* Native Development Kit (NDK) What is it?  Build scripts/toolkit to incorporate native code in Android* apps via the Java Native Interface (JNI) Why use it?  Performance  e.g., complex algorithms, multimedia applications, games  Differentiation  app that takes advantage of direct CPU/HW access  e.g., using SSSE3 for optimization  Fluid and lag-free animations  Software code reuse Why not use it?  Performance improvement isn’t always guaranteed, in contrary to the added complexity 5
  • 5. NDK Application Development C/C++ Code Makefile ndkbuild Mix with Java* GDB debug Using JNI Android* Applications Java Application SDK APIs Java Framework JNI Native Libs Bionic C Library 6 NDK APIs
  • 6. NDK Platform Dalvik* Application Android* NDK Application Java* Native Library Java Source Compile with Javac Compile with Javac Dynamic Library Java Native Library Class Android app Class Compile and Link C Code Create C header with javah -jni C/C++ Source Code Header file Application Files Makefile Optional thanks to JNI_Onload 7
  • 7. Compatibility with Standard C/C++ Bionic C Library:  Lighter than standard GNU C Library  Not POSIX compliant  pthread support included, but limited  No System-V IPCs  Access to Android* system properties Bionic is not binary-compatible with the standard C library It means you generally need to (re)compile everything using the Android NDK toolchain 8
  • 8. Android* C++ Support By default, libstdc++ is used. It lacks:  Standard C++ Library support (except some headers)  C++ exceptions support  RTTI support Fortunately, you have other libs available with the NDK: Runtime Exceptions RTTI STL system No No No gabi++ Yes Yes No stlport Yes Yes Yes gnustl Yes Yes Yes Choose which library to compile against in your Makefile (Application.mk file): APP_STL := gnustl_shared Postfix the runtime with _static or _shared For using C++ features, you also need to enable these in your Makefile: LOCAL_CPP_FEATURES += exceptions rtti 9
  • 9. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Summary and Q&A Break • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 10
  • 10. Installing the Android* NDK NDK is a platform dependant archive: It provides:  A build environment PIDs  Android* headers and PSI libraries TS  Documentation and samples (these are very useful) You can integrate it with Eclipse ADT: We’ll talk about Android studio integration later  11
  • 11. Manually Adding Native Code to an Android* Project Standard Android* Project Structure 1. Create JNI folder for native sources Native Sources - JNI Folder 2. Reuse or create native c/c++ sources 3. Create Android.mk Makefile NDK-BUILD will automatically create ABI libs folders. 4. Build Native libraries using NDKBUILD script. 12
  • 12. Adding NDK Support to your Eclipse Android* Project 13
  • 13. Android* NDK Samples Sample App Type hello-jni Call a native function written in C from Java*. bitmap-plasma Access an Android* Bitmap object from C. san-angeles EGL and OpenGL* ES code in C. hello-gl2 EGL setup in Java and OpenGL ES code in C. native-activity C only OpenGL sample (no Java, uses the NativeActivity class). native-plasma C only OpenGL sample (also uses the NativeActivity class). … 14
  • 14. Focus on Native Activity Only native code in the project android_main() entry point running in its own thread Event loop to get input data and frame drawing messages /** * This is the main entry point of a native application that is using * android_native_app_glue. It runs in its own thread, with its own * event loop for receiving input events and doing other things. */ void android_main(struct android_app* state); 15
  • 15. Integrating Native Functions with Java* Declare native methods in your Android* application (Java*) using the ‘native’ keyword: public native String stringFromJNI(); PIDs PSI Provide a native shared library built with the NDK that contains the methods used by TS your application: libMyLib.so Your application must load the shared library (before use… during class load for example): static { System.loadLibrary("MyLib"); } There is two ways to associate your native code to the Java methods: javah and JNI_OnLoad 16
  • 16. Javah Method “javah” helps automatically generate the appropriate JNI header stubs based on the Java* source files from the compiled Java classes files: Example: > javah –d jni –classpath bin/classes com.example.hellojni.HelloJni Generates com_example_hellojni_HelloJni.h file with this definition: JNIEXPORT jstring JNICALL Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEn v *, jobject); 17
  • 17. Javah Method ... { ... tv.setText( stringFromJNI() ); ... } public native String stringFromJNI(); static { System.loadLibrary("hello-jni"); } C function that will be automatically mapped: jstring Java_com_example_hellojni_HelloJni_stringFromJNI(JNIEnv* env, jobject thiz ) { return (*env)->NewStringUTF(env, "Hello from JNI !"); } 18
  • 18. JNI_OnLoad Method – Why ? Proven method No more surprises after methods registration Less error prone when refactoring Add/remove native functions easily No symbol table issue when mixing C/C++ code Best spot to cache Java* class object references 19
  • 19. JNI_OnLoad Method In your library name your functions as you wish and declare the mapping with JVM methods: jstring stringFromJNI(JNIEnv* env, jobject thiz) { return env->NewStringUTF("Hello from JNI !"); } static JNINativeMethod exposedMethods[] = { {"stringFromJNI","()Ljava/lang/String;",(void*)stringFromJNI}, } ()Ljava/lang/String; is the JNI signature of the Java* method, you can retrieve it using the javap utility: > javap -s -classpath binclasses -p com.example.hellojni.HelloJni Compiled from "HelloJni.java“ … public native java.lang.String stringFromJNI(); Signature: ()Ljava/lang/String; … 20
  • 20. JNI_OnLoad Method extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved) { JNIEnv* env; if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) return JNI_ERR; jclass clazz = env->FindClass("com/example/hellojni/HelloJni"); if(clazz==NULL) return JNI_ERR; env->RegisterNatives(clazz, exposedMethods, sizeof(exposedMethods)/sizeof(JNINativeMethod)); env->DeleteLocalRef(clazz); return JNI_VERSION_1_6; } JNI_OnLoad is the library entry point called during load. Here it applies the mapping previously defined. 21
  • 21. Memory Handling of Java* Objects Memory handling of Java* objects is done by the JVM: You only deal with references to these objects Each time you get a reference, you must not forget to delete it after use local references are automatically deleted when the native call returns to Java References are local by default Global references are only created by NewGlobalRef() 22
  • 22. Creating a Java* String C: jstring string = (*env)->NewStringUTF(env, "new Java String"); C++: jstring string = env->NewStringUTF("new Java String"); Memory is handled by the JVM, jstring is always a reference. You can call DeleteLocalRef() on it once you finished with it. By the way: Main difference with compiling JNI code in C or in C++ is the nature of “env” as you can see it here Remember that otherwise, the API is the same 23
  • 23. Getting a C/C++ String from Java* String const char *nativeString = (*env)>GetStringUTFChars(javaString, null); … (*env)->ReleaseStringUTFChars(env, javaString, nativeString); //more secure and efficient: int tmpjstrlen = env->GetStringUTFLength(tmpjstr); char* fname = new char[tmpjstrlen + 1]; env->GetStringUTFRegion(tmpjstr, 0, tmpjstrlen, fname); fname[tmpjstrlen] = 0; … delete fname; 24
  • 24. Handling Java* Exceptions // call to java methods may throw Java exceptions jthrowable ex = (*env)->ExceptionOccurred(env); if (ex!=NULL) { (*env)->ExceptionClear(env); // deal with exception } (*env)->DeleteLocalRef(env, ex); 25
  • 25. JNI Primitive Types Java* Type Description boolean jboolean unsigned 8 bits byte jbyte signed 8 bits char jchar unsigned 16 bits short jshort signed 16 bits int jint signed 32 bits long jlong signed 64 bits float jfloat 32 bits double jdouble 64 bits void 26 Native Type void N/A
  • 26. JNI Reference Types jobjectArray jbooleanArray jclass jbyteArray jstring jcharArray jarray jshortArray jthrowable jintArray jobject jlongArray jfloatArray Arrays elements are manipulated using Get<type>ArrayElements() and Get/Set<type>ArrayRegion() jdoubleArray Don’t forget to call ReleaseXXX() for each GetXXX() call. 27
  • 27. Calling Java* Methods On an object instance: jclass clazz = (*env)->GetObjectClass(env, obj); jmethodID mid = (*env)->GetMethodID(env, clazz, "methodName", "(…)…"); if (mid != NULL) (*env)->Call<Type>Method(env, obj, mid, parameters…); Static call: jclass clazz = (*env)->FindClass(env, "java/lang/String"); jmethodID mid = (*env)->GetStaticMethodID(env, clazz, "methodName", "(…)…"); if (mid != NULL) (*env)->CallStatic<Type>Method(env, clazz, mid, parameters…); • (…)…: method signature • parameters: list of parameters expected by the Java* method • <Type>: Java method return type 28
  • 28. Throwing Java* Exceptions jclass clazz = (*env->FindClass(env, "java/lang/Exception"); if (clazz!=NULL) (*env)->ThrowNew(env, clazz, "Message"); The exception will be thrown only when the JNI call returns to Java*, it will not break the current native code execution. 29
  • 29. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Break • Summary and Q&A • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 30
  • 30. NDK Applications support on Intel® Platforms  Most will run w/o any recompilation…  Android NDK provides an x86 toolchain since 2011  A simple recompile using the Android NDK yields the best performance  If there is specific processor dependent code, porting may be necessary 31
  • 31. Configuring NDK Target ABIs Include all ABIs by setting APP_ABI to all in jni/Application.mk: APP_ABI=all Build ARM v7a libs Build ARM v5 libs Build x86 libs Build mips libs The NDK will generate optimized code for all target ABIs You can also pass APP_ABI variable to ndk-build, and specify each ABI: ndk-build APP_ABI=x86 32
  • 32. Fat Binaries By default, an APK contains libraries for every supported ABIs. libs/armeabi Use lib/armeabi libraries libs/armeabi-v7a libs/x86 … Android project Use lib/armeabi-v7a libraries Use lib/x86 libraries The application will be filtered during installation (after download) 33
  • 33. Multiple APKs Google Play* supports multiple APKs for the same application. What compatible APK will be chosen for a device entirely depends on the android:VersionCode If you have multiple APKs for multiple ABIs, best is to simply prefix your current version code with a digit representing the ABI: 2310 ARMv7 6310 x86 You can have more options for multiple APKs, here is a convention that will work if you’re using all of these: 34
  • 34. Uploading Multiple APKs to the store Switch to Advanced mode before uploading the second APK. The interface almost doesn’t change. But if you upload a new apk in simple mode, it will overwrite the former one. You can get the same screen than on the right. even if the new package will not overwrite the previous one. 35
  • 35. Uploading Multiple APKs to the store Don’t forget to use different version codes for your different APKs. 36
  • 36. Memory Alignment By default struct TestStruct { int mVar1; long long mVar2; int mVar3; }; Easy fix struct TestStruct { int mVar1; long long mVar2 __attribute__ ((aligned(8))); int mVar3; }; 37
  • 37. SIMD Instructions NEON* instruction set on ARM* platforms MMX™, Intel® SSE, SSE2, SSE3, SSSE3 on Intel® Atom™ processor based platforms http://intel.ly/10JjuY4 - NEONvsSSE.h : wrap NEON functions and intrinsics to SSE3 – 100% covered //******* definition sample ***************** int8x8_t vadd_s8(int8x8_t a, int8x8_t b); // VADD.I8 d0,d0,d0 #ifdef USE_MMX #define vadd_s8 _mm_add_pi8 //MMX #else #define vadd_s8 _mm_add_epi8 #endif //… Supplemental Streaming SIMD Extensions (SSSE) Intel® Streaming SIMD Extensions (Intel® SSE) Optimization Notice 38 Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision #20110804
  • 38. Multiple Code Paths Compiler macros #ifdef __i386__ strlcat(buf, "__i386__", sizeof(buf)); #endif #ifdef __arm__ strlcat(buf, "__arm__", sizeof(buf)); #endif • Directly inside source code • No runtime overhead #ifdef _MIPS_ARCH • Works with all build configurations strlcat(buf, "_MIPS_ARCH", sizeof(buf)); #endif 39
  • 39. Multiple Code Paths Inside Makefiles ifeq ($(TARGET_ARCH_ABI),x86) … else … endif 40
  • 40. 3rd party libraries x86 support Game engines/libraries with x86 support: • Havok Anarchy SDK: android x86 target available • Unreal Engine 3: android x86 target available • Marmalade: android x86 target available • Cocos2Dx: set APP_ABI in Application.mk • FMOD: x86 lib already included, set ABIs in Application.mk • AppGameKit: x86 lib already included, set ABIs in Application.mk • libgdx: x86 lib now available in latest releases • … No x86 support but works on consumer devices: • • 41 Corona Unity
  • 41. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Summary and Q&A Break • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 42
  • 42. Debugging with logcat NDK provides log API in <android/log.h>: int __android_log_print(int prio, const char *tag, const char *fmt, ...) Usually used through this sort of macro: #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "APPTAG", __VA_ARGS__)) Example: LOGI("accelerometer: x=%f y=%f z=%f", x, y, z); 43
  • 43. Debugging with logcat To get more information on native code execution: adb shell setprop debug.checkjni 1 (already enabled by default in the emulator) And to get memory debug information (root only): adb shell setprop libc.debug.malloc 1 -> leak detection adb shell setprop libc.debug.malloc 10 -> overruns detection adb shell start/stop -> reload environment 44
  • 44. Debugging with GDB and Eclipse Native support must be added to your project Pass NDK_DEBUG=1 to the ndk-build command, from the project properties: NDK_DEBUG flag is supposed to be automatically set for a debug build, but this is not currently the case. 45
  • 45. Debugging with GDB and Eclipse* When NDK_DEBUG=1 is specified, a “gdbserver” file is added to your libraries 46
  • 46. Debugging with GDB and Eclipse* Debug your project as a native Android* application: 47
  • 47. Debugging with GDB and Eclipse From Eclipse “Debug” perspective, you can manipulate breakpoints and debug your project Your application will run before the debugger is attached, hence breakpoints you set near application launch will be ignored 48
  • 48. Valgrind The Valgrind tool suite provides a number of debugging and profiling tools that help you make your programs faster and more correct. Memcheck : It can detect many memory-related errors that are common in C and C++ programs and that can lead to crashes and unpredictable behavior. Setting up Valgrind  Download latest version on Valgrind from http://valgrind.org/downloads/  ./configure  Make  Sudo make install Steps above should install valgrind. Compile your program with -g to include debugging information so that Memcheck's error messages include exact line numbers.  gcc myprog.c valgrind --leak-check=yes myprog arg1 arg2 ; Memcheck is the default tool. The --leak-check option turns on the detailed memory leak detector. You can also invoke the leak check like this  Valgrind ./a.out 49 Use “–o” to optimize the program while compiling. Any other option slows down Valgrind to a significant extent.
  • 49. Interpreting Valgrind error messages Example of output message from Valgrind Memcheck ==19182== Invalid write of size 4 ==19182== at 0x804838F: f (example.c:6) ==19182== by 0x80483AB: main (example.c:11)  19182 : Process ID  “Invalid write..” is the error message  6 and 11 are line numbers Add “--gen-suppressions=yes ” to suppress errors arising out of pre compiled libs and other mem leak errors that you cannot make changes to. Memcheck cannot detect every memory error your program has. For example, it can't detect out-of-range reads or writes to arrays that are allocated statically or on the stack. But it should detect many errors that could crash your program Suggested reading : http://valgrind.org/docs/manual/manual.html 50
  • 50. Valgrind on Android x86 Installing Valgrind  Download this package: https://my.syncplicity.com/share/7cse0vnb43auckm/valgrind-x86-androidemulator  Unzip and enter root of the unzipped package.  Install valgrind on the emulator using these commands:  adb push Inst /  adb shell chmod 777 /data/local/Inst  adb shell chmod 755 /data/local/Inst/bin/*  adb shell chmod 755 /data/local/Inst/lib/valgrind/* Setting up a program to be run with Valgrind  adb shell setprop wrap.com.example.hellojni "logwrapper /data/local/Inst/bin/valgrind“ #Replace package name with your package name  Next startups of your app will be wrapped by valgrind and you'll see the output inside logcat. Please note  These binaries are compatible with Intel HAXM 4.0.3 x86 emulator, not the 4.3.  You can use any OS as host  To use valgrind on a real device, you need to recompile valgrind for it (you can read the .sh file inside the zip to get the right cmd and adapt it) and you need to be root on it. 51
  • 51. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Summary and Q&A Break • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 52
  • 52. Vectorization SIMD instructions up to SSSE3 available on current Intel® Atom™ processor based platforms, Intel® SSE4.2 on the Intel Silvermont Microarchitecture 0 127 X4 X3 X2 X1 Y4 Y3 Y2 Y1 X4◦Y4 X3◦Y3 X2◦Y2 X1◦Y1 SSSE3, SSE4.2 Vector size: 128 bit Data types: • 8, 16, 32, 64 bit integer • 32 and 64 bit float VL: 2, 4, 8, 16 On ARM*, you can get vectorization through the ARM NEON* instructions Two classic ways to use these instructions: Compiler auto-vectorization Compiler intrinsics Supplemental Streaming SIMD Extensions (SSSE) Intel® Streaming SIMD Extensions (Intel® SSE) Optimization Notice Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision #20110804 53
  • 53. GCC Flags ifeq ($(TARGET_ARCH_ABI),x86) LOCAL_CFLAGS += -O3 -ffast-math -mtune=atom -msse3 -mfpmath=sse else LOCAL_CFLAGS += ... endif To optimize for Intel Silvermont Microarchitecture (available starting with NDK r9 gcc-4.8 toolchain): LOCAL_CFLAGS += -O3 -ffast-math -mtune=slm -msse4.2 -mfpmath=sse ffast-math influence round-off of fp arithmetic and so breaks strict IEEE compliance The other optimizations are totally safe Add -ftree-vectorizer-verbose to get a vectorization report Optimization Notice Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision #20110804 54
  • 54. Agenda • The Android* Native Development Kit (NDK) • Developing an application that uses the NDK • Supporting several CPU architectures • Summary and Q&A Break • Debugging • Optimizing • Intel® Tools and Libraries • Summary and Q&A 55
  • 55. Faster Android* Emulation on Intel® Architecture Based Host PC Pre-built Intel® Atom™ Processor Images Android* SDK manager has x86 emulation images built-in To emulate an Intel Atom processor based Android phone, install the “Intel Atom x86 System Image” available in the Android SDK Manager Much Faster Emulation Intel® Hardware Accelerated Execution Manager (Intel® HAXM) for Mac and Windows uses Intel® Virtualization Technology (Intel® VT) to accelerate Android emulator Intel VT is already supported in Linux* by KVM 56 Intel x86 Atom System Image Intel x86 Emulator Accelerator
  • 56. Intel® Threading Building Blocks (Intel® TBB) Specify tasks instead of manipulating threads  Intel® Threading Building Blocks (Intel® TBB) maps your logical tasks onto threads with full support for nested parallelism Targets threading for scalable performance  Uses proven efficient parallel patterns  Uses work-stealing to support the load balance of unknown execution time for tasks Open source and licensed versions available on: Linux*, Windows*, Mac OS X* and… Android* Open Source version available on: http://threadingbuildingblocks.org/ Licensed version available on: http://software.intel.com/en-us/intel-tbb 57
  • 57. Components of TBB (version 4.2) Parallel algorithms Flow Graphs parallel_for parallel_for_each parallel_reduce parallel_do parallel_scan parallel_pipeline & filters parallel_sort parallel_invoke functional nodes (source, continue, function) buffering nodes (buffer, queue, sequencer) split/join nodes other nodes Ranges and partitioners Tasks & Task groups Task scheduler Synchronization primitives atomic operations mutexes : classic, recursive, spin, queuing rw_mutexes : spin, queuing Thread Local Storage combinable enumerable_thread_specific flattened2d Concurrent containers concurrent_hash_map concurrent_queue concurrent_bounded_queue concurrent_priority_queue concurrent_vector concurrent_unordered_map concurrent_unordered_set Memory allocators tbb_allocator, cache_aligned_allocator, scalable_allocator 58
  • 58. Intel® TBB – Integration #for including tbb in your project: Android.mk include $(CLEAR_VARS) LOCAL_MODULE := tbb LOCAL_SRC_FILES := $(TBB_PATH)/lib/android/libtbb.so LOCAL_EXPORT_C_INCLUDES := $(TBB_PATH)/include include $(PREBUILT_SHARED_LIBRARY) #for calling tbb from your lib: LOCAL_CPP_FEATURES := rtti exceptions LOCAL_SHARED_LIBRARIES += tbb LOCAL_CFLAGS += -DTBB_USE_GCC_BUILTINS -std=c++11 APP_STL := gnustl_shared System.loadLibrary("gnustl_shared"); System.loadLibrary("tbb"); System.loadLibrary("YourLib"); 59 Application.mk Java
  • 59. Intel® Threading Building Blocks (Intel® TBB) Example #include <tbb/parallel_reduce.h> #include <tbb/blocked_range.h> Lambda function with Calculating aa one- Pi Defining a reduction Computes part of Defining range and initial value as dimensional range within the range r over a range function parm double getPi() { const int num_steps = 10000000; const double step = 1./num_steps; double pi = tbb::parallel_reduce( tbb::blocked_range<int>(0, num_steps), //Range double(0), //Value //function [&](const tbb::blocked_range<int>& r, double current_sum ) -> double { for (size_t i=r.begin(); i!=r.end(); ++i) { double x = (i+0.5)*step; current_sum += 4.0/(1.0 + x*x); } return current_sum; // updated value of the accumulator }, []( double s1, double s2 ) { //Reduction return s1+s2; } ); return pi*step; } 60
  • 60. Intel® Graphics Performance Analyzer (Intel® GPA): System Analyzer Profiles performance and Power Real-time charts of CPU, GPU and power metrics Conduct real-time experiments with OpenGL-ES* (with state overrides) to help narrow down problems Triage system-level performance with CPU, GPU and Power metrics Available freely on intel.com/software/gpa 61
  • 61. Intel® Graphics Performance Analyzer (Intel® GPA): How to Use the System Analyzer 1. Install APK, and connect to Host PC via adb 62 2. Run Intel® GPA System Analyzer on development machine 3. View Profile
  • 62. Intel® C++ Compiler for Android* • Based on Intel® C/C++ Compiler XE 14.0 for Linux* • Integrates into the Android* NDK as additional toolchain • Supports Intel® Atom™ processor optimization • 79.95$ Available on http://software.intel.com/c-compiler-android 63
  • 63. Project Anarchy* • Complete mobile game engine that includes Havok Vision Engine, Physics, Animation Studio and AI • Free to publish on Android (ARM and x86), iOS, and Tizen • C++ development environment • Efficient asset management system • LUA scripting and debugging • Extensible source code and full library of sample materials • Remote debugging • File serving for live asset updates • Remote input • Visual debugger http://www.projectanarchy.com/ 64
  • 64. Summary Use the NDK for performance critical applications and code reuse It is easy to target multiple architectures Our tools can help you getting most out of it 65
  • 65. Where to Get More Info Getting Started Technical Content Android Blogs Support Forums Intel® Developer Zone (Intel® DZ) • Real developers sharing knowledge and offering help • Dedicated communities and forums focused on your interests • Worldwide reach • News and insights on cutting edge technology Android Developer on Intel Website Great content you won’t find anywhere else Technical articles, tools, and guides Native app porting tips & case studies Info on x86 emulator and Intel® Hardware Accelerated Execution Manager • Active forums and blogs written by Intel and community experts • • • • www.intel.com/software/android 66
  • 66. Resources http://developer.android.com/tools/sdk/ndk/index.html - NDK http://docs.oracle.com/javase/6/docs/technotes/guides/jni/spec/intro.html - JNI documentation http://software.intel.com/en-us/blogs/2012/12/12/from-arm-neon-to-intel-mmxsse-automatic-portingsolution-tips-and-tricks - Automatic porting of NEON* instructions http://software.intel.com/en-us/blogs/2012/11/28/intel-for-android-developers-learning-series - Android* learning series http://software.intel.com/en-us/articles/android-application-development-and-optimization-on-the-intel-atomplatform - NDK Apps Development http://software.intel.com/en-us/articles/creating-and-porting-ndk-based-android-apps-for-ia/ - NDK Apps porting http://software.intel.com/en-us/articles/android-texture-compression - Textures Compression http://software.intel.com/en-us/articles/how-to-debug-an-app-for-android-x86-and-the-tools-to-use/ - NDK Apps debugging http://software.intel.com/en-us/articles/android-tutorial-writing-a-multithreaded-application-using-intelthreading-building-blocks - TBB Android* Tutorial http://developer.android.com/training/ - Google Android* developer guide 67
  • 67. Legal Disclaimer INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT. A "Mission Critical Application" is any application in which failure of the Intel Product could result, directly or indirectly, in personal injury or death. SHOULD YOU PURCHASE OR USE INTEL'S PRODUCTS FOR ANY SUCH MISSION CRITICAL APPLICATION, YOU SHALL INDEMNIFY AND HOLD INTEL AND ITS SUBSIDIARIES, SUBCONTRACTORS AND AFFILIATES, AND THE DIRECTORS, OFFICERS, AND EMPLOYEES OF EACH, HARMLESS AGAINST ALL CLAIMS COSTS, DAMAGES, AND EXPENSES AND REASONABLE ATTORNEYS' FEES ARISING OUT OF, DIRECTLY OR INDIRECTLY, ANY CLAIM OF PRODUCT LIABILITY, PERSONAL INJURY, OR DEATH ARISING IN ANY WAY OUT OF SUCH MISSION CRITICAL APPLICATION, WHETHER OR NOT INTEL OR ITS SUBCONTRACTOR WAS NEGLIGENT IN THE DESIGN, MANUFACTURE, OR WARNING OF THE INTEL PRODUCT OR ANY OF ITS PARTS. Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined". Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information. The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request. Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order. Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-5484725, or go to: http://www.intel.com/design/literature.htm Silvermont and other code names featured are used internally within Intel to identify products that are in development and not yet publicly announced for release. Customers, licensees and other third parties are not authorized by Intel to use code names in advertising, promotion or marketing of any product or services and any such use of Intel's internal code names is at the sole risk of the user. Intel, Atom, Look Inside and the Intel logo are trademarks of Intel Corporation in the United States and other countries. *Other names and brands may be claimed as the property of others. Copyright ©2013 Intel Corporation. 68
  • 68. Legal Disclaimer Roadmap Notice: All products, computer systems, dates and figures specified are preliminary based on current expectations, and are subject to change without notice. Intel® Virtualization Technology (Intel® VT) requires a computer system with an enabled Intel® processor, BIOS, and virtual machine monitor (VMM). Functionality, performance or other benefits will vary depending on hardware and software configurations. Software applications may not be compatible with all operating systems. Consult your PC manufacturer. For more information, visit http://www.intel.com/go/virtualization. Software Source Code Disclaimer: Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 69
  • 69. Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision #20110804 70
  • 70. Risk Factors The above statements and any others in this document that refer to plans and expectations for the third quarter, the year and the future are forward-looking statements that involve a number of risks and uncertainties. Words such as “anticipates,” “expects,” “intends,” “plans,” “believes,” “seeks,” “estimates,” “may,” “will,” “should” and their variations identify forward-looking statements. Statements that refer to or are based on projections, uncertain events or assumptions also identify forwardlooking statements. Many factors could affect Intel’s actual results, and variances from Intel’s current expectations regarding such factors could cause actual results to differ materially from those expressed in these forward-looking statements. Intel presently considers the following to be the important factors that could cause actual results to differ materially from the company’s expectations. Demand could be different from Intel's expectations due to factors including changes in business and economic conditions; customer acceptance of Intel’s and competitors’ products; supply constraints and other disruptions affecting customers; changes in customer order patterns including order cancellations; and changes in the level of inventory at customers. Uncertainty in global economic and financial conditions poses a risk that consumers and businesses may defer purchases in response to negative financial events, which could negatively affect product demand and other related matters. Intel operates in intensely competitive industries that are characterized by a high percentage of costs that are fixed or difficult to reduce in the short term and product demand that is highly variable and difficult to forecast. Revenue and the gross margin percentage are affected by the timing of Intel product introductions and the demand for and market acceptance of Intel's products; actions taken by Intel's competitors, including product offerings and introductions, marketing programs and pricing pressures and Intel’s response to such actions; and Intel’s ability to respond quickly to technological developments and to incorporate new features into its products. The gross margin percentage could vary significantly from expectations based on capacity utilization; variations in inventory valuation, including variations related to the timing of qualifying products for sale; changes in revenue levels; segment product mix; the timing and execution of the manufacturing ramp and associated costs; start-up costs; excess or obsolete inventory; changes in unit costs; defects or disruptions in the supply of materials or resources; product manufacturing quality/yields; and impairments of long-lived assets, including manufacturing, assembly/test and intangible assets. Intel's results could be affected by adverse economic, social, political and physical/infrastructure conditions in countries where Intel, its customers or its suppliers operate, including military conflict and other security risks, natural disasters, infrastructure disruptions, health concerns and fluctuations in currency exchange rates. Expenses, particularly certain marketing and compensation expenses, as well as restructuring and asset impairment charges, vary depending on the level of demand for Intel's products and the level of revenue and profits. Intel’s results could be affected by the timing of closing of acquisitions and divestitures. Intel's results could be affected by adverse effects associated with product defects and errata (deviations from published specifications), and by litigation or regulatory matters involving intellectual property, stockholder, consumer, antitrust, disclosure and other issues, such as the litigation and regulatory matters described in Intel's SEC reports. An unfavorable ruling could include monetary damages or an injunction prohibiting Intel from manufacturing or selling one or more products, precluding particular business practices, impacting Intel’s ability to design its products, or requiring other remedies such as compulsory licensing of intellectual property. A detailed discussion of these and other factors that could affect Intel’s results is included in Intel’s SEC filings, including the company’s most recent reports on Form 10-Q, Form 10-K and earnings release. Rev. 7/17/13 71