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

2019 年 3 月 9 日 AI100

编译的目的是将源码转化为机器可识别的可执行程序,在早期,每次编译都需要重新构建所有东西,后来人们意识到可以让编译器自动完成一些工作,从而提升编译效率。

但“编译器不过是用于代码生成的软机器,你可以使用你想要的任何语言来生成代码”,真的是必要的吗?


作者 | 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 中的线性求解器(linear solver),就像我们使用 C 和 C ++ 一样,此处代码为:

# 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

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

# 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) + "\n"
    copy_code += "%" + str(I+2)
    copy_code += " = load double, double* %" + str(I+1)
    copy_code += ", align 8\n"
    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) + "\n"
    self.code += "store double %" + str(I)
    self.code += ", double* %" + str(I+1) + ", align 8\n"
    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]) + "\n";
    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)


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

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

# 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[2if 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)

实现解算器的整段代码提供了 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

Step 2. LLVM 汇编语言

Step 3. 调用替换后的 LLVM

Step 4. 本地优化装配

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

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

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

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

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

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


结论


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

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

本文涉及的所有测试均在 Intel(R)Core(TM)i7-7700HQ CPU @ 2.80GHz 上进行,代码使用 Clang 3.8.0-2ubuntu4 和 g++5.4.0 编译。

基准测试源代码:

https://github.com/akalenuk/wordsandbuttons/tree/master/exp/python_to_llvm

原文链接:

https://wordsandbuttons.online/outperforming_everything_with_anything.html

本文为 CSDN 翻译,如需转载,请注明来源出处。


(本文为 AI科技大本营转载文章,转载请联系原作者)


4 月13日-4 月14日,CSDN 将在北京主办“Python 开发者日( 2019 )”,汇聚十余位来自阿里巴巴IBM英伟达等国内外一线科技公司的Python技术专家,还有数百位来自各行业领域的Python开发者。目前购票通道已开启,早鸟票限量发售中,3 月15日之前可享受优惠价 299 元(售完即止)。


推荐阅读:

                         

点击“阅读原文”,查看历史精彩文章。

登录查看更多
1

相关内容

编译器(Compiler),是一种计算机程序,它会将用某种编程语言写成的源代码(原始语言),转换成另一种编程语言(目标语言)。
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
最新《自动微分手册》77页pdf
专知会员服务
97+阅读 · 2020年6月6日
Python导论,476页pdf,现代Python计算
专知会员服务
254+阅读 · 2020年5月17日
【干货书】R语言书: 编程和统计的第一课程,
专知会员服务
107+阅读 · 2020年5月9日
Python分布式计算,171页pdf,Distributed Computing with Python
专知会员服务
105+阅读 · 2020年5月3日
【新书】Python编程基础,669页pdf
专知会员服务
186+阅读 · 2019年10月10日
一个牛逼的 Python 调试工具
机器学习算法与Python学习
15+阅读 · 2019年4月30日
使用 C# 和 Blazor 进行全栈开发
DotNet
6+阅读 · 2019年4月15日
34个最优秀好用的Python开源框架
专知
9+阅读 · 2019年3月1日
教程 | PyTorch经验指南:技巧与陷阱
机器之心
15+阅读 · 2018年7月30日
教程 | 从头开始了解PyTorch的简单实现
机器之心
20+阅读 · 2018年4月11日
快乐的迁移到 Python3
Python程序员
5+阅读 · 2018年3月25日
为什么你应该学 Python ?
计算机与网络安全
4+阅读 · 2018年3月24日
Arxiv
4+阅读 · 2019年8月7日
Arxiv
12+阅读 · 2018年1月12日
Arxiv
26+阅读 · 2017年12月6日
VIP会员
相关VIP内容
【2020新书】使用高级C# 提升你的编程技能,412页pdf
专知会员服务
56+阅读 · 2020年6月26日
最新《自动微分手册》77页pdf
专知会员服务
97+阅读 · 2020年6月6日
Python导论,476页pdf,现代Python计算
专知会员服务
254+阅读 · 2020年5月17日
【干货书】R语言书: 编程和统计的第一课程,
专知会员服务
107+阅读 · 2020年5月9日
Python分布式计算,171页pdf,Distributed Computing with Python
专知会员服务
105+阅读 · 2020年5月3日
【新书】Python编程基础,669页pdf
专知会员服务
186+阅读 · 2019年10月10日
相关资讯
一个牛逼的 Python 调试工具
机器学习算法与Python学习
15+阅读 · 2019年4月30日
使用 C# 和 Blazor 进行全栈开发
DotNet
6+阅读 · 2019年4月15日
34个最优秀好用的Python开源框架
专知
9+阅读 · 2019年3月1日
教程 | PyTorch经验指南:技巧与陷阱
机器之心
15+阅读 · 2018年7月30日
教程 | 从头开始了解PyTorch的简单实现
机器之心
20+阅读 · 2018年4月11日
快乐的迁移到 Python3
Python程序员
5+阅读 · 2018年3月25日
为什么你应该学 Python ?
计算机与网络安全
4+阅读 · 2018年3月24日
Top
微信扫码咨询专知VIP会员