Speculative: Rust for base system components
Alan Somers
asomers at freebsd.org
Sun Jan 6 17:17:24 UTC 2019
On Sun, Jan 6, 2019 at 9:54 AM Brian Neal <brian at aceshardware.com> wrote:
>
> I don't have it anymore, but yours is close enough. When compiling your
> first example, I get 156 instructions, including map iterators and rust
> result assert/unwrap logic. Your second example produces 21 lines,
> including a loop iterator:
>
> rustc 1.31.0 with -C opt-level=s:
>
> <I as core::iter::traits::IntoIterator>::into_iter:
> mov eax, edi
> mov edx, esi
> ret
> example::oddcount2:
> xor eax, eax
> test edi, edi
> jle .LBB1_3
> xor ecx, ecx
> .LBB1_2:
> mov edx, ecx
> and edx, 1
> neg edx
> and edx, ecx
> lea esi, [rcx + 1]
> add eax, edx
> mov ecx, esi
> cmp edi, esi
> jne .LBB1_2
> .LBB1_3:
> ret
Those 21 lines aren't 21 instructions; you're counting labels. Also,
the first three instructions aren't actually part of the function.
They're dead code, and should be eliminate by LTO. However, Rust
doesn't do LTO when compiling libraries; only when linking
executables. The unwrap logic, etc is also not part of the function.
So in this example, Rust produces only a few more instructions than C.
Also, FYI the Rust expression "0..num" is exclusive on the right.
It's equivalent to C's "for (int i = 0; i < num; i++)", though that
doesn't change the instruction count.
-Alan
>
> Converting to C:
>
> int oddcount2(int num) {
> int sum = 0;
> for (int i = 0; i <= num; ++i)
> {
> if (i % 2 > 0)
> {
> sum += i;
> }
> }
> return sum;
> }
>
> I get the following with gcc 8.2 using -Os:
>
> oddcount2(int):
> xor edx, edx
> xor eax, eax
> .L4:
> cmp edx, edi
> jg .L1
> test dl, 1
> je .L3
> add eax, edx
> .L3:
> inc edx
> jmp .L4
> .L1:
> ret
>
> Cheers,
>
> -Brian
>
> On 1/6/2019 8:01 AM, Alan Somers wrote:
> > I get different results on Godbolt. I don't know exactly what your
> > program was, but I tried to recreate it from your description. I
> > wrote it in two ways. With opt-level=s, I got 13 instructions for one
> > version, and 16 for the other. With opt-level=3, I got vectorized
> > code for both. Here's my code:
> >
> > pub fn oddcount(num: i32) -> i32 {
> > (0..num).map(|i| {
> > if i % 2 > 0 {
> > i
> > } else {
> > 0
> > }
> > }).sum()
> > }
> >
> > pub fn oddcount2(num: i32) -> i32 {
> > let mut sum = 0;
> > for i in 0..num {
> > if i % 2 > 0 {
> > sum += i;
> > }
> > }
> > sum
> > }
> >
> > -Alan
> > _______________________________________________
> > freebsd-hackers at freebsd.org mailing list
> > https://lists.freebsd.org/mailman/listinfo/freebsd-hackers
> > To unsubscribe, send any mail to "freebsd-hackers-unsubscribe at freebsd.org"
> >
More information about the freebsd-hackers
mailing list