Python的INT功能表现 [英] Python's int function performance

查看:201
本文介绍了Python的INT功能表现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请问Python的内置函数 INT 仍试图提交的值转换,即使该值已经是一个整数

Does Python's built-in function int still try to convert the submitted value even if the value is already an integer?

更简洁:是否有 INT('42') INT(42)之间造成任何性能差异通过转换算​​法?

More concisely: is there any performance difference between int('42') and int(42) caused by conversion algorithm?

推荐答案

由于每在源$ C ​​$ C 意见,

转换一个数字或字符串为整数,或者如果没有参数返回0
  给出。如果x是一个数字,返回 X .__ INT __ ()。对于浮点
  数字,这截断向零。

Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.

如果x不是数字或如果基给出,则x必须是字符串,
  字节或ByteArray实例重新presenting在字面整数
  定基

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base

所以,如果输入的是一个数字, __ __ INT 函数将被调用该对象上,结果将被退回。在内部 nb_int 是PyNumberMethods项目结构,对应于 __ __ INT 功能。根据在写这篇文章,<一个时间的最新源$ C ​​$ C href=\"http://hg.python.org/cpython/file/d8f48717b74e/Objects/longobject.c#l4954\"><$c$c>long_long是对应于 nb_int 功能,这是这样定义的函数

So, if the input is a number, __int__ function will be called on that object and the result will be returned. Internally nb_int is an item in PyNumberMethods structure, which corresponds to the __int__ function. As per the latest source code at the time of this writing, long_long is the function which corresponds to the nb_int function, which is defined like this

long_long(PyObject *v)
{
    if (PyLong_CheckExact(v))
        Py_INCREF(v);
    else
        v = _PyLong_Copy((PyLongObject *)v);
    return v;
}

下面<一个href=\"http://hg.python.org/cpython/file/d8f48717b74e/Include/longobject.h#l16\"><$c$c>PyLong_checkExact是一个宏观的,刚刚检查,如果当前的对象实际上是long类型。如果这是真的,它只是增加了引用计数,因为它是返回对象,没什么特别之处就完成了。

Here PyLong_checkExact is a Macro, which just checks if the current object is really of type long. If it is true, it simply increases the reference count and returns the object as it is, nothing extra is done.

如果输入是在一个字符串的形式中,串必须被转换为数字同<一href=\"http://hg.python.org/cpython/file/d8f48717b74e/Objects/longobject.c#l2336\"><$c$c>PyLong_FromUni$c$cObject功能。

If the input is in the form of a string, the string has to be converted to a number with PyLong_FromUnicodeObject function.

这篇关于Python的INT功能表现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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