每次除法时,我都可以禁用零除法检查吗? [英] Can I disable checking for zero division every time the division happens?

查看:83
本文介绍了每次除法时,我都可以禁用零除法检查吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了更好地了解Rusts的恐慌/异常机制,我编写了以下代码:

In order to better understand Rusts panic/exception mechanisms, I wrote the following piece of code:

#![feature(libc)]

extern crate libc;

fn main() {
    let mut x: i32;
    unsafe {
      x = libc::getchar();
    }

    let y = x - 65;
    println!("{}", x);

    let z = 1 / y;
    println!("{}", z);
}

我想检查Rust如何处理除以零的情况.最初,我认为它要么是面对未处理的SIGFPE并垂死,要么是实施了处理程序并将其重新路由为紧急状态(如今可以解决?).

I wanted to check how Rust deals with division by zero cases. Originally I assumed it was either taking an unhandled SIGFPE to the face and dying or it implemented a handler and rerouted it to a panic (which can be dealt with nowadays?).

代码很冗长,因为我想确保Rust在编译时知道某些东西为零,因此用户输入时,不会做任何聪明"的事情.只要给它一个"A",它就可以解决问题.

The code is verbose because I wanted to make sure that Rust does not do anything "smart" when it knows at compile-time that something is zero, hence the user input. Just give it an 'A' and it should do the trick.

我发现Rust实际上在每次除法之前都会生成检查零除法的代码.我什至只看了一次大会.:-)

I found out that Rust actually produces code that checks for zero division every time before the division happens. I even looked at the assembly for once. :-)

长话短说:我可以禁用此行为吗?我想对于较大的数据集,这可能会对性能产生很大的影响.为什么不使用我们的CPU能力为我们检测这些东西呢?我可以设置自己的信号处理程序并代替SIGFPE吗?

Long story short: Can I disable this behaviour? I imagine for larger datasets this can have quite a performance impact. Why not use our CPUs ability to detect this stuff for us? Can I set up my own signal handler and deal with the SIGFPE instead?

根据 Github上的一个问题,情况在某些时候一定有所不同以前.

According to an issue on Github the situation must have been different some time ago.

我认为事先检查每个部门离零成本"还很遥远.你怎么看?我缺少明显的东西吗?

I think checking every division beforehand is far away from "zero-cost". What do you think? Am I missing something obvious?

推荐答案

长话短说:我可以禁用此行为吗?

Long story short: Can I disable this behaviour?

是的,您可以: std :: intrinsics:: unchecked_div(a,b) .您的问题也适用于余数(这就是Rust调用取模的方式):此处进行了检查,以将其与C ++进行比较.

Yes you can: std::intrinsics::unchecked_div(a, b). Your question also applies to remainder (thats how Rust calls modulo): std::intrinsics::unchecked_rem(a, b). I checked the assembly output here to compare it to C++.

在文档中指出:

这是仅夜间使用的实验API.(core_intrinsics)

This is a nightly-only experimental API. (core_intrinsics)

内部技术不太可能被稳定,相反,应该通过标准库其余部分中的稳定接口来使用它们

intrinsics are unlikely to ever be stabilized, instead they should be used through stabilized interfaces in the rest of the standard library

因此,您必须使用夜间版本,并且由于 Matthieu的原因,不太可能以稳定的形式进入标准库M.已经指出.

So you have to use the nightly build and it is unlikely to ever come in a stabilized form to the standard library for the reasons Matthieu M. already pointed out.

这篇关于每次除法时,我都可以禁用零除法检查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆