C言語の「clock()関数」のサンプルプログラムです。
- #include <time.h>
- clock_t clock();
- clock()関数は、プログラムの実行開始から数えたシステム時計のサイクル数を返します。秒数を算出するには。この値をCLOCKS_PER_SECマクロで割ります。
目次
ソースコード
[clock.c]
#include <stdio.h>
#include <time.h> /* clock() */
void waitMSec( int msec )
{
clock_t end;end = clock() + ( CLOCKS_PER_SEC * msec / 1000 );
while( clock() < end );
}
void waitAndReport( int msec )
{
static int idx = 0;
clock_t beg;beg = clock();
waitMSec( msec );
printf( "%2d, msec: %4d, CLOCKS: %lu - %lu\n", ++idx, msec, beg, clock() ) ;
}
int main( void )
{
printf( "CLOCKS_PER_SEC = %d\n", CLOCKS_PER_SEC );waitAndReport( 300 );
waitAndReport( 1 );
waitAndReport( 1000 );return 0 ;
}
実行例
Windows 10, Visual Studio 2022「x86 Native Tools Command Prompt for VS 2022」
>cl /Fe:clock_win.exe clock.c
>clock_win.exe
CLOCKS_PER_SEC = 1000
1, msec: 300, CLOCKS: 0 - 300
2, msec: 1, CLOCKS: 300 - 301
3, msec: 1000, CLOCKS: 301 - 1301>
Cygwin 3.3.6-1 ( gcc 11.3.0 )
$ gcc -Wall -O2 -o clock_cyg clock.c
$ ./clock_cyg.exe
CLOCKS_PER_SEC = 1000
1, msec: 300, CLOCKS: 15 - 327
2, msec: 1, CLOCKS: 327 - 342
3, msec: 1000, CLOCKS: 342 - 1343$