C++ でコードスニペットの実行時間を計算する方法 質問する

C++ でコードスニペットの実行時間を計算する方法 質問する

C++ コード スニペットの実行時間を秒単位で計算する必要があります。Windows または Unix マシンのいずれかで動作している必要があります。

これを実行するには、次のコードを使用します。(前にインポート)

clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;

ただし、小さな入力や a = a + 1 などの短いステートメントの場合は、「0 秒」という結果が返されます。0.0000001 秒かそのくらいの値になると思います。

System.nanoTime()この場合、Java では非常にうまく機能することを覚えています。ただし、 clock()C++ の関数からまったく同じ機能を取得することはできません。

解決策はありますか?

ベストアンサー1

私が書いたこの関数を使用できます。 を呼び出すGetTimeMs64()と、システム クロックを使用して、UNIX エポックからの経過時間をミリ秒単位で返します。 と同じですがtime(NULL)、単位はミリ秒です。

Windows と Linux の両方で動作し、スレッドセーフです。

Windows では粒度は 15 ミリ秒であることに注意してください。Linux では実装に依存しますが、通常は 15 ミリ秒です。

#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif

/* Remove if already defined */
typedef long long int64; typedef unsigned long long uint64;

/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
 * windows and linux. */

uint64 GetTimeMs64()
{
#ifdef _WIN32
 /* Windows */
 FILETIME ft;
 LARGE_INTEGER li;

 /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
  * to a LARGE_INTEGER structure. */
 GetSystemTimeAsFileTime(&ft);
 li.LowPart = ft.dwLowDateTime;
 li.HighPart = ft.dwHighDateTime;

 uint64 ret = li.QuadPart;
 ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
 ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */

 return ret;
#else
 /* Linux */
 struct timeval tv;

 gettimeofday(&tv, NULL);

 uint64 ret = tv.tv_usec;
 /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
 ret /= 1000;

 /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
 ret += (tv.tv_sec * 1000);

 return ret;
#endif
}

おすすめ記事