1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

プログラムを高速化するにはどの書き方が適切か

Posted at

組み込みでCを使うとき、どの書き方が高速なのか知りたかったので、単純なプログラムでどの書き方が高速にできるか検証してみました。

環境

開発環境:MPLAB X IDE v5.50
使用言語:C言語
コンパイラ:XC8 v2.32
マイコン:PIC16F73
クロック周波数:16MHz

基本のプログラム

PORTCのRC0をトグルするプログラムです。RC0がLOWの時はRC0をHIGHにし、RC0がHIGHの時はRC0をLOWにします。
MPLAB X IDEのシミュレータのストップウォッチ機能で測定しました。

結論

単純な処理はif文が速いのでif文を使ったほうが良さそうです。動作は同じでも、プログラムによって処理時間が大幅に変わることが分かりました。

プログラム サイクル数 実行時間
if文 7~8 1.75~2μs
switch文 16~17 4~4.25μs
NOT代入 12~13 3~3.25μs
排他的論理和代入 12 3μs
三項演算子 12~13 3~3.25μs

if文

main.c
# include <xc.h>

void main(void) {
    TRISC = 0b00000000;
    PORTC = 0b00000000;
    while(1){
        if(PORTCbits.RC0 == 0){
            PORTCbits.RC0 = 1;
        }
        else{
            PORTCbits.RC0 = 0;
        }
    }
}

測定結果(1ループ当たり)
7~8サイクル(1.75~2μs)

switch文

main.c
# include <xc.h>

void main(void) {
    TRISC = 0b00000000;
    PORTC = 0b00000000;
    while(1){
        switch(PORTCbits.RC0){
            case 0:
                PORTCbits.RC0 = 1;
                break;
            default :
                PORTCbits.RC0 = 0;
                break;
        }
    }
}

測定結果(1ループ当たり)
16~17サイクル(4~4.25μs)

NOT代入

main.c
# include <xc.h>

void main(void) {
    TRISC = 0b00000000;
    PORTC = 0b00000000;
    while(1){
        PORTCbits.RC0 = ~PORTCbits.RC0;
    }
}

測定結果(1ループ当たり)
12~13サイクル(3~3.25μs)

排他的論理和代入

main.c
# include <xc.h>

void main(void) {
    TRISC = 0b00000000;
    PORTC = 0b00000000;
    while(1){
        PORTCbits.RC0 ^= 1;
    }
}

測定結果(1ループ当たり)
12サイクル(3μs)

三項演算子

main.c
# include <xc.h>

void main(void) {
    TRISC = 0b00000000;
    PORTC = 0b00000000;
    while(1){
        PORTCbits.RC0 = (PORTCbits.RC0 == 0) ? 1 : 0;
    }
}

測定結果(1ループ当たり)
12~13サイクル(3~3.25μs)

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?