有没有办法进一步优化这个MIPs代码?

时间:2014-02-15 23:02:35

标签: c mips

int strlen( char* string ) {
    int count = 0;
    while( *string != ‘\0’ ) {
        string++;
        count++;
    }
    return count;
}

我正在研究这些......
我想知道你是否可以提出任何优化建议? 以下是MIP代码......

strlen:
li $t0, 0 # initialize the count to zero
loop:
lbu $t1, 0($a0) # load the next character into t1
beqz $t1, exit # check for the null character
addi $a0, $a0, 1 # increment the string pointer
addi $t0, $t0, 1 # increment the count
j loop # return to the top of the loop
exit:

3 个答案:

答案 0 :(得分:0)

 // will (probably) output x86_64 assembly (or your computer's native assembly)
 gcc -Wall -S test.c


 // will output mips3 assembly
 gcc -Wall -march=mips3 -S test.c

或者通过优化:

 // will output (optimized) mips3 assembly (if possible)
 gcc -Wall -O3 -march=mips3 -S test.c

答案 1 :(得分:0)

好吧,你可以优化C,虽然在优化器中弄清楚你被允许这样做可能很棘手。将您的代码与:

进行比较
int strlen( char* string ) {
    char *sp = string;
    while( *sp != ‘\0’ ) sp++;
    return sp - string;
}

这应该意味着主循环只包含一个addi语句而不是2。

答案 2 :(得分:0)

不知道MIPS,但你可以删除一些命令:

strlen:
li $t0, $a0     # init ptr
loop:
lbu $t1, 0($t0) # load the next character into t1
beqz $t1, exit # check for the null character
addi $t0, $t0, 1 # increment the string pointer
j loop # return to the top of the loop
exit:
sub $v0, $t0, $a0