都有Python了,还要什么编译器!

编译的目的是将源码转化为机器可识别的可执行程序,在早期,每次编译都需要重新构建所有东西,后来人们意识到可以让编译器自动完成一些工作,从而提升编译效率。但“编译器不过是用于代码生成的软机器,你可以使用你想要的任何语言来生成代码”,真的是必要的吗?

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

作者 | Oleksandr Kaleniuk译者 | 虎说责编 | 仲培艺来源 | CSDN(ID:CSDNnews)

诚然,编译器可以为你生成高性能的代码,但是你真的需要编译器吗?另一种方法是用 Assembly 编写程序,虽然有点夸大,但这种方法有两个主要缺陷:

1. 汇编代码不可移植;

2. 虽然在现代工具的辅助下变得容易了些,但 Assembly 编程仍然需要大量繁琐的工作。

值得庆幸的是,我们都生活在二十一世纪,这两个问题都已得到解决。第一个解决方案是 LLVM,最初,它意味着“低级虚拟机”,这正是我们可以确保可移植性的原因。简而言之,它需要用一些非常低级别的与硬件无关语言编写的代码,并为特定的硬件平台返回一些高度优化的原生代码。使用 LLVM,我们既具有低级编程的强大功能,又具有面向硬件微优化的自动化功能。

第二个问题的解决方法是使用“脚本”语言,Scheme、Python、Perl,甚至 bash 或 AWK 都可以消除繁琐的工作。

实验计划

首先,让我们生成一个完全内联展开的解决方案,并将其嵌入到基准测试代码中。该计划如下:

1. 使用 Clang 为基准生成 LLVM 中间代码,该基准用于测量 solve_5,一个不存在的函数;

2. 使 Python 在 LLVM 中生成线性求解器(linear solver)代码;

3. 使用 Python 脚本测试基准,用生成求解器替换 solve_5 调用;

4. 使用 LLVM 静态编译器将中间代码转换为机器代码;

5. 使用 GNU 汇编器和 Clang 的链接器将机器代码转换为可执行的二进制文件。

这就是它在 Makefile 中的样子:

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

Python 部分

我们需要 Python 中的线性求解器(linear solver),就像我们使用 C 和 C ++ 一样,此处代码为:

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;”># this generates n-solver in LLVM code with LLVMCode objects.

No LLVM stuff yet, just completely Pythonic solution

def solve_linear_system(a_array, b_array, x_array, n_value):
def a(i, j, n):
if n == n_value:
return a_array[i * n_value + j]
return a(i, j, n+1)a(n, n, n+1) – a(i, n, n+1)a(n, j, n+1)
def b(i, n):
if n == n_value:
return b_array[i]
return a(n, n, n+1)b(i, n+1) – a(i, n, n+1)b(n, n+1)
def x(i):
d = b(i,i+1)
for j in range(i):
d -= a(i, j, i+1) * x_array[j]
return d / a(i, i, i+1)
for k in range(n_value):
x_array[k] = x(k)
return x_array
</pre>

当我们用数字运行时,我们可以得到数字。但我们想要代码,因此,我们需要制作一个假装成数字的对象(Object)来探测算法。该对象记录下算法想要执行的每一个操作,并准备好集成 LLVM 中间语言。

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;”># this is basically the whole LLVM layer
I = 0
STACK = []
class LLVMCode:

the only constructor for now is by double* instruction

def init(self, io, code = ”):
self.io = io
self.code = code
def getitem(self, i):
global I, STACK
copy_code = “%” + str(I+1)
copy_code += ” = getelementptr inbounds double, double* “
copy_code += self.io +”, i64 ” + str(i) + “

copy_code += “%” + str(I+2)
copy_code += ” = load double, double* %” + str(I+1)
copy_code += “, align 8

I += 2
STACK += [I]
return LLVMCode(self.io, copy_code)
def setitem(self, i, other_llvcode):
global I, STACK
self.code += other_llvcode.code
self.code += “%” + str(I+1)
self.code += ” = getelementptr inbounds double, double* “
self.code += self.io +”, i64 ” + str(i) + “

self.code += “store double %” + str(I)
self.code += “, double* %” + str(I+1) + “, align 8

I += 1
STACK = STACK[:-1]
return self
def general_arithmetics(self, operator, other_llvcode):
global I, STACK
self.code += other_llvcode.code;
self.code += “%” + str(I+1) + ” = f” + operator
self.code += ” double %” + str(STACK[-2]) + “, %”
self.code += str(STACK[-1]) + “
“;
I += 1
STACK = STACK[:-2] + [I]
return self
def add(self, other_llvcode):
return self.general_arithmetics(‘add’, other_llvcode)
def sub(self, other_llvcode):
return self.general_arithmetics(‘sub’, other_llvcode)
def mul(self, other_llvcode):
return self.general_arithmetics(‘mul’, other_llvcode)
def div(self, other_llvcode):
return self.general_arithmetics(‘div’, other_llvcode)
</pre>

接着,当我们使用这种对象运行求解器时,我们得到了一个用 LLVM 中间语言编写的全功能线性求解器。然后我们将其放入基准代码中进行速度测试(看它有多快)。

LLVM 中的指令有编号,我们希望保存枚举,因此将代码插入到基准测试中的函数很重要,但也不是很复杂。

<pre style=”-webkit-tap-highlight-color: transparent; box-sizing: border-box; font-family: Consolas, Menlo, Courier, monospace; font-size: 16px; white-space: pre-wrap; position: relative; line-height: 1.5; color: rgb(153, 153, 153); margin: 1em 0px; padding: 12px 10px; background: rgb(244, 245, 246); border: 1px solid rgb(232, 232, 232); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: start; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px;”># this replaces the function call

and updates all the instructions’ indices

def replace_call(text, line, params):
global I, STACK

‘%12 ‘ -> 12

I = int(”.join(
[xi for xi in params[2] if xi.isdigit()]
))
first_instruction_to_replace = I + 1
STACK = []
replacement = solve_linear_system(
LLVMCode(params[0]),
LLVMCode(params[1]),
LLVMCode(params[2]), 5).code
delta_instruction = I – first_instruction_to_replace + 1
for i in xrange(first_instruction_to_replace, sys.maxint):
not_found = sum(
[text.find(‘%’ + str(i) + c) == -1
for c in POSSIBLE_CHARS_NUMBER_FOLLOWS_WITH]
)
if not_found == 4:

the last instruction has already been substituted

break
new_i = i + delta_instruction
for c in POSSIBLE_CHARS_NUMBER_FOLLOWS_WITH:

substitute instruction number

text = text.replace(‘%’ + str(i) + c, ‘%’ + str(new_i) + c)
return text.replace(line, replacement)
</pre>

实现解算器的整段代码提供了 Python-to-LLVM 层,其中代码插入只有 100 行!

另附 GitHub 链接:https://github.com/akalenuk/wordsandbuttons/blob/master/exp/python_to_llvm/exp_embed_on_call/substitute_solver_call.py

基准

基准测试本身在 C 中。当我们运行 Makefile 时,它对 solve_5 的调用被 Python 生成的 LLVM 代码所取代。

Step 1. Benchmark C source code

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

Step 2. LLVM 汇编语言

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

Step 3. 调用替换后的 LLVM

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

Step 4. 本地优化装配

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

最值得注意的是 Python 脚本生成的超冗长中间代码如何变成一些非常紧凑且非常有效的硬件代码。同时它也是高度标量化的,但它是否足以与 C 和 C++ 的解决方案竞争呢?

以下是三种情况的近似数字(带有技巧的 C、C++ 与基于 LLVM 的 Python 的性能对比):

1. C 的技巧对 Clang 来说并不适用,因此测量 GCC 版本,其平均运行大约 70 毫秒;

2. C++ 版本是用 Clang 构建的,运行时间为 60 毫秒;

3. Python 版本(此处描述的版本)仅运行 55 毫秒。

《都有Python了,还要什么编译器!》 都有Python了,还要什么编译器!

当然,这种加速并不是关键,但这表明你可以用 Python 编写出胜过用 C 或 C++ 编写的程序。这也就暗示你不必学习一些特殊语言来创建高性能的应用程序或库。

结论

快速编译语言和慢速脚本语言之间的对立不过是虚张声势。原生代码生成的可能不是核心功能,而是类似于可插拔选项。像是 Python 编译器 Numba 或 Lua 的 Terra,其优势就在于你可以用一种语言进行研究和快速原型设计,然后使用相同的语言生成高性能的代码。

高性能计算没有理由保留编译语言的特权,编译器只是用于代码生成的软机器。你可以使用你想要的任何语言生成代码,我相信如果你愿意,你可以教 Matlab 生成超快的 LLVM 代码。

    原文作者:Python小老弟
    原文地址: https://www.jianshu.com/p/541fef3fbf9a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞