今まで以下のような秒単位の時間計測関数を、Android用とWindows用にそれぞれ作って使っていました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double GetTime() | |
{ | |
timespec t; | |
clock_gettime(CLOCK_MONOTONIC, &t); | |
return (double)t.tv_sec + (double)t.tv_nsec / 1000000000; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double GetTime() | |
{ | |
LARGE_INTEGER t, f; | |
QueryPerformanceCounter(&t); | |
QueryPerformanceFrequency(&f); | |
return (double)t.QuadPart / f.QuadPart; | |
} |
今更ながら、C++11のstd::chronoでどちらでも動く関数を書けることに気づき、以下のように書きなおしました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
double GetTime() | |
{ | |
static auto start = std::chrono::high_resolution_clock::now(); | |
auto now = std::chrono::high_resolution_clock::now(); | |
return std::chrono::duration_cast<std::chrono::duration<double, std::ratio<1, 1>>>(now - start).count(); | |
} |
static auto startが妙ですが、こうするとGetTimeの初回呼び出し時の時間をstartに記録できます。あとは毎回のGetTimeの呼び出しでstartからの経過時間を秒単位で返します。
#include <chrono> で "fatal error: chrono: No such file or directory"というエラーが出てしまう場合、build.gradleでgnustlを使うよう設定する必要があります。build.gradleの一部を抜粋します。
"stlport_static"ではだめで、"gnustl_static"を使う必要があるようです。android-ndk-r10d\sources\cxx-stl\stlport\stlportにはchronoが入っていないのに対し、android-ndk-r10d\sources\cxx-stl\gnu-libstdc++\4.9\includeには入っていました。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
android { | |
defaultConfig { | |
ndk { | |
moduleName 'AdamasNative' | |
cFlags "-std=c++11" | |
ldLibs "log" | |
ldLibs "GLESv3" | |
abiFilters "armeabi", "mips", "x86" | |
stl "gnustl_static" | |
} | |
} | |
} |