我正在使用 Java 编写 Android 应用程序。我还使用 jni 接口来调用本机函数。 例如:
JNIEXPORT jint JNICALL Java_com_app_Native_test(JNIEnv *env, jobject object)
{
steady_clock::time_point begin = steady_clock::now();
int lenght = 500000000;
int * arr1 = new int[lenght];
for(int i = 0; i < lenght; i++)
{
*(arr1+i) = i+1;
}
matrix<int, 100> matrix1(arr1, lenght);
steady_clock::time_point end = steady_clock::now();
return duration_cast<microseconds>(end-begin).count();
}
此函数测量创建数组(arr1)和对象(matrix1)所需的时间。问题是该函数总是返回 0。事实上,这是不可能的。如果您为取决于对象的时间添加一个值,那么一切都会按预期进行。那就是:
return duration_cast<microseconds>(end-begin).count()+matrix1(1, 1);
//matrix1(1, 1) = 1
在这种情况下,如果我不想不断地添加依赖于对象的值,我该怎么办?
我采用了您的代码并添加了
matrix
的虚拟定义,它仅存储提供的指针和总长度:
template <class T, size_t width>
struct matrix {
matrix(T* ptr, size_t len) : ptr(ptr), len(len) {}
T* ptr;
size_t len;
};
Clang 删除了测量之间的所有代码:(编译器资源管理器链接)
Java_com_app_Native_test(): # @Java_com_app_Native_test()
push rbx
call std::chrono::_V2::steady_clock::now()@PLT
mov rbx, rax
call std::chrono::_V2::steady_clock::now()@PLT
// function epilogue follows
如果您确实以某种方式使用了
matrix
实例,编译器将被迫经历完整的初始化过程。