验证参数为0或1 [英] Validate parameter for 0 or 1

查看:138
本文介绍了验证参数为0或1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

INT 的参数 NUM 输入,用户可以给它两个值之一: 0 1 。结果
我可以用明显的检查:

I have a parameter num of int type, where the user can give it one of two values: 0 or 1.
I can check it using the obvious:

if (num < 0 || num > 1)
    print("The parameter value is incorrect.\n");

但我在想,如果有一个更好的(更快?少code?)这样做呢?

But I was wondering if there was a better (faster? less code?) to do this?

修改结果
这是一些数据流code,所以性能是至关重要的。我在找一个更快的方法来运行这个检查。

EDIT
This is some data flow code, so performance is of the essence. I am looking for a faster way to run this check.

感谢

推荐答案

您基本上是作出有关实际编译器的行为错误的假设。在这两种情况下,即:

Clear code over (naive) micro-optimizations

You are essentially making wrong assumptions about actual compiler's behavior. In both cases, that is:

if (num < 0 || num > 1) { ...

if (num != 0 && num != 1) { ...

优化编译器的无论如何都会缩短到最短的形式。您可能会看到,都产生相同的组件,这可能看起来(x86平台):

an optimizing compiler will reduce it anyway into shortest form. You may see that, both generate the same assembly, that might look as (x86 platform):

cmp    $0x1,%eax
jbe    1e <foo+0x1e> # jump if below or equal

这已经足够快,如 CMP 指令在所有主要的架构已经的一周期的延迟。

This is already fast enough, as cmp instruction on all major architectures has latency of one cycle.

底线是选择什么code,使你的意图明确你的,将来的维护,让编译器完成其工作。只要确保,你有适当的优化级别(例如 -O2 或更好)进行设置。

The bottom line is to choose whatever code, that makes your intent clear for you, future maintainers and let the compiler do its job. Just make sure, that you set it with proper optimization level (e.g. -O2 or better).

不过,如果性能是真的在这里重要的(?你异形它作为这样,难道你),那么你可以考虑一下另一种优化,即在的 分支prediction 水平(假设你的CPU有对它的支持)。海湾合作委员会有 __ builtin_expect 征,其允许暗示编译器,在大多数情况下的分支将采取或不

However, if performance is really crucial here (and you profiled it as so, don't you?), then you could think about another kind of optimization, that is at branch prediction level (assuming that your CPU has support for it). The GCC has __builtin_expect intrinsic, that allows to hint compiler, that in most cases branch will be taken or not.

您可以使用 __ builtin_expect 来提供支编译
  prediction信息。一般情况下,你应该preFER用实际
  天寒这个(-fprofile弧)的反馈,因为程序员
  出了名的坏predicting他们的程序实际上是如何执行。
  但是,也有在该数据难以收集应用

You may use __builtin_expect to provide the compiler with branch prediction information. In general, you should prefer to use actual profile feedback for this (-fprofile-arcs), as programmers are notoriously bad at predicting how their programs actually perform. However, there are applications in which this data is hard to collect.

举例来说,如果你有信心,该功能采用 0 1 病例aproximately 99%数量,那么你可以把它写成:

For instance, if you are confident, that function takes 0 or 1 in aproximately 99% number of cases, then you could write it as:

#define unlikely(x) __builtin_expect((x), 0)

if (unlikely(num != 0 && num != 1)) { ...

这篇关于验证参数为0或1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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