gpt4 book ai didi

Python+C 比纯 C 快(稍微)快

转载 作者:太空狗 更新时间:2023-10-29 15:39:54 28 4
gpt4 key购买 nike

我一直在用各种语言和实现实现相同的代码(在 Blackjack 中发牌而不爆牌的方法的数量)。我注意到的一个奇怪之处是,Python 在 C 中调用分区函数的实现实际上比用 C 编写的整个程序快一点。其他语言似乎也是如此(Ada vs Python 调用 Ada,Nim vs Python 调用尼姆)。这对我来说似乎违反直觉 - 知道这怎么可能吗?

所有代码都在我的 GitHub 仓库中:

https://github.com/octonion/puzzles/tree/master/blackjack

这是 C 代码,使用“gcc -O3 outcomes.c”编译。

#include <stdio.h>

int partitions(int cards[10], int subtotal)
{
//writeln(cards,subtotal);
int m = 0;
int total;
// Hit
for (int i = 0; i < 10; i++)
{
if (cards[i] > 0)
{
total = subtotal + i + 1;
if (total < 21)
{
// Stand
m += 1;
// Hit again
cards[i] -= 1;
m += partitions(cards, total);
cards[i] += 1;
}
else if (total == 21)
{
// Stand; hit again is an automatic bust
m += 1;
}
}
}
return m;
}

int main(void)
{
int deck[] =
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 16 };
int d = 0;

for (int i = 0; i < 10; i++)
{
// Dealer showing
deck[i] -= 1;
int p = 0;
for (int j = 0; j < 10; j++)
{
deck[j] -= 1;
int n = partitions(deck, j + 1);
deck[j] += 1;
p += n;
}

printf("Dealer showing %i partitions = %i\n", i, p);
d += p;
deck[i] += 1;
}
printf("Total partitions = %i\n", d);
return 0;
}

这是 C 函数,使用“gcc -O3 -fPIC -shared -o libpartitions.so partitions.c”编译。

int partitions(int cards[10], int subtotal)
{
int m = 0;
int total;
// Hit
for (int i = 0; i < 10; i++)
{
if (cards[i] > 0)
{
total = subtotal + i + 1;
if (total < 21)
{
cards[i] -= 1;
// Stand
m += 1;
// Hit again
m += partitions(cards, total);
cards[i] += 1;
}
else if (total == 21)
{
// Stand; hit again is an automatic bust
m += 1;
}
}
}
return m;
}

这是 C 函数的 Python 包装器:

#!/usr/bin/env python

from ctypes import *
import os

test_lib = cdll.LoadLibrary(os.path.abspath("libpartitions.so"))
test_lib.partitions.argtypes = [POINTER(c_int), c_int]
test_lib.partitions.restype = c_int

deck = ([4]*9)
deck.append(16)

d = 0

for i in xrange(10):
# Dealer showing
deck[i] -= 1
p = 0
for j in xrange(10):
deck[j] -= 1
nums_arr = (c_int*len(deck))(*deck)
n = test_lib.partitions(nums_arr, c_int(j+1))
deck[j] += 1
p += n
print('Dealer showing ', i,' partitions =',p)
d += p
deck[i] += 1

print('Total partitions =',d)

最佳答案

我认为这里的原因是 GCC 如何在 2 种情况下编译函数 partitions。您可以使用 objdump 比较 outcomes 二进制可执行文件和 libpartitions.so 中的 asm 代码以查看差异。

objdump -d -M intel <file name>

构建共享库时,GCC 不知道如何调用 partitions。而在 C 程序中,GCC 确切地知道何时调用 partitions(然而,在这种情况下,会导致更差的性能)。这种上下文差异使得 GCC 以不同的方式进行优化。

您可以尝试不同的编译器来比较结果。我已经检查过 GCC 5.4 和 Clang 6.0。使用 GCC 5.4,Python 脚本运行速度更快,而使用 Clang,C 程序运行速度更快。

关于Python+C 比纯 C 快(稍微)快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49228106/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com