11
8

More than 5 years have passed since last update.

for文とWhile文を速度計測

Posted at

久々にC言語に触れたのでなんとなく。
コンパイラはVC2013のCL。

コンパイルオプションは、/Ot /FAをつけます。

計測対象

time_while.c
#include <stdio.h>
#include <time.h>

int main(void)
{
    clock_t start, end;
    int i=0;
    int a=0;

    start = clock();

    while(i<10000*10000) { 
        ++a;
        ++i;
    }
    end = clock();

    printf("%.10lf[s]\n", (double)(end - start)/CLOCKS_PER_SEC);

    return 0;
}

ループ文だけ変えます。

time_for.c
#include <stdio.h>
#include <time.h>

int main(void)
{
    clock_t start, end;
    int i=0;
    int a=0;

    start = clock();

    for( ;i<10000*10000; ++i) { 
        ++a;
    }
    end = clock();

    printf("%.10lf[s]\n", (double)(end - start)/CLOCKS_PER_SEC);

    return 0;
}

計測結果

While文
0.2320000000[s]
for文
0.2800000000[s]

意外と差がつきました。

アセンブリ

長かったので、ループ部分だけ抜き出してみた。

time_while.asm
; Line 10
    call    _clock
    mov DWORD PTR _start$[ebp], eax
$LN2@main:
; Line 12
    cmp DWORD PTR _i$[ebp], 100000000       ; 05f5e100H
    jge SHORT $LN1@main
; Line 13
    mov eax, DWORD PTR _a$[ebp]
    add eax, 1
    mov DWORD PTR _a$[ebp], eax
; Line 14
    mov ecx, DWORD PTR _i$[ebp]
    add ecx, 1
    mov DWORD PTR _i$[ebp], ecx
; Line 15
    jmp SHORT $LN2@main
$LN1@main:
; Line 16
    call    _clock
    mov DWORD PTR _end$[ebp], eax
time_for.asm
; Line 10
    call    _clock
    mov DWORD PTR _start$[ebp], eax
; Line 12
    jmp SHORT $LN3@main
$LN2@main:
    mov eax, DWORD PTR _i$[ebp]
    add eax, 1
    mov DWORD PTR _i$[ebp], eax
$LN3@main:
    cmp DWORD PTR _i$[ebp], 100000000       ; 05f5e100H
    jge SHORT $LN1@main
; Line 13
    mov ecx, DWORD PTR _a$[ebp]
    add ecx, 1
    mov DWORD PTR _a$[ebp], ecx
; Line 14
    jmp SHORT $LN2@main
$LN1@main:
; Line 15
    call    _clock
    mov DWORD PTR _end$[ebp], eax

for文だと、最初にジャンプがあるというくらいの差かな。
加算処理を頭に置いているからジャンプしなければならない、と。

ふむふむ。

11
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8