为什么函数总是返回零经过时间?

问题描述 投票:0回答:1

我正在使用 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

在这种情况下,如果我不想不断地添加依赖于对象的值,我该怎么办?

c++ benchmarking
1个回答
0
投票

我采用了您的代码并添加了

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
实例,编译器将被迫经历完整的初始化过程。这是基准测试中非常常见的问题,也是您应该避免自己进行滚动的原因。例如,请参阅 Google Benchmark 文档中的“防止优化”部分。 (并在将来切换到基准测试)

© www.soinside.com 2019 - 2024. All rights reserved.