処理時間を計測する
ちょっと画像処理とかもやってみたいんだよね。
いくら正確に動作するプログラムが書けても、処理速度が使い物にならないほど遅くてはダメです。そんな時はプログラムを見直して最適化を図る訳ですが、改善前後の指標がないと意味がないです。*1この指標は、処理時間だったりCPUのクロックカウント数だったりします。
ということで、ちょっとプログラムを書いてみました。後者のCPUのクロックカウント数を調べる方で。
概要
処理時間をCPUのクロックカウント数から割り出すプログラム。
TimeStampCounter.hpp
#ifndef __TIME_STAMP_COUNTER_HPP__ #define __TIME_STAMP_COUNTER_HPP__ class TimeStampCounter { public: TimeStampCounter(); void start(); unsigned long long end(); private: unsigned long long time_; }; #endif // __TIME_STAMP_COUNTER_HPP__
TimeStampCounter.cpp
#include <cstddef> #include "TimeStampCounter.hpp" const std::size_t AVE_TIMES = 100; #ifdef _WIN32 #include <intrin.h> int CPUInfo[4]; #else #define RDTSC(X) \ do { \ __asm__ __volatile__ ("cpuid" : : : "rax", "rbx", "rcx", "rdx"); \ __asm__ __volatile__ ( \ "rdtsc\n\t" \ "shlq $32, %%rdx\n\t" \ "orq %%rdx, %%rax\n\t" \ "movq %%rax, %0" : "=g" (X) : : "rax", "rdx"); \ } while (0) #endif static unsigned long long getTime() { #ifdef _WIN32 __cpuid(CPUInfo,1); return __rdtsc(); #else unsigned long long ret; RDTSC(ret); return ret; #endif } TimeStampCounter::TimeStampCounter() : time_(getTime()) { } void TimeStampCounter::start() { time_ = getTime(); } unsigned long long TimeStampCounter::end() { unsigned long long now = getTime(); return now > time_ ? now - time_ : 0; }
CPUのクロック周波数計測
Sleepの精度とかはちょっと置いておいて、CPUのクロック周波数を調べたい場合は、1秒間スリープさせます。
#include <cstdio> #include "TimeStampCounter.hpp" #ifdef _WIN32 #include <Windows.h> #pragma comment (lib, "TimeStampCounter.lib") #else #include <sys/unistd.h> #endif int main(int argc, char** argv) { TimeStampCounter counter; counter.start(); #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif unsigned long long hz = counter.end(); printf("CPU frequency : %lld Hz\n", hz); }