我想尝试制作自己的绝对值函数。我认为计算绝对值的最快方法是简单地屏蔽符号位(IEEE 754 中的最后一位)。我想将它的速度与标准abs功能进行比较。这是我的实现:
// Union used for type punning
union float_uint_u
{
float f_val;
unsigned int ui_val;
};
// 'MASK' has all bits == 1 except the last one
constexpr unsigned int MASK = ~(1 << (sizeof(int) * 8 - 1));
float abs_bitwise(float value)
{
float_uint_u ret;
ret.f_val = value;
ret.ui_val &= MASK;
return ret.f_val;
}
Run Code Online (Sandbox Code Playgroud)
作为记录,我知道这种类型的双关语不是标准的 C++。但是,这仅用于教育目的,根据文档,这在 GCC 中得到支持。
我认为这应该是计算绝对值的最快方法,因此它至少应该与标准实现一样快。但是,对随机值的 100000000 次迭代计时,我得到了以下结果:
Bitwise time: 5.47385 | STL time: 5.15662
Ratio: 1.06152
Run Code Online (Sandbox Code Playgroud)
我的abs函数慢了大约 6%。 …
所以我在python中编写了一个小脚本,它带有一个带有2个按钮和一个文本字段的gui.您键入文本区域并单击加密,文本突然看起来很疯狂.coooooool.
但是当你点击解密时,它不会回到原来的状态.这是代码
from Tkinter import *
import ttk
root = Tk()
textArea = Text(root, state = "normal")
def encrypt():
message = textArea.get('1.0', 'end')
newMessage = ''
lastChar = ''
for c in message:
if lastChar != '':
newMessage += chr((ord(c) + ord(lastChar)) % 256)
lastChar = chr((ord(c) + ord(lastChar)) % 256)
else:
newMessage += chr((ord(c) + 5) % 256)
lastChar = chr((ord(c) + 5) % 256)
textArea.delete('1.0', 'end')
textArea.insert('end', newMessage)
def decrypt():
message = textArea.get('1.0', 'end')
newMessage = ''
lastChar …Run Code Online (Sandbox Code Playgroud)