Python+C(略)比纯C快

2024-05-29 03:20:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用各种语言和实现实现实现了相同的代码(在21点中处理一手牌而不被破坏的方法)。我注意到的一个奇怪的现象是,Python在C中调用partitions函数的实现实际上比用C编写的整个程序要快一些。其他语言似乎也是如此(Ada vs Python调用Ada,Nim vs Python调用Nim)。我觉得这有悖常理-你知道这怎么可能吗?在

代码都在我的GitHub repo中:

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

下面是使用“gcc-O3 outcourts.C”编译的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;
}

下面是使用'gcc-O3-fPIC-shared-o编译的C函数libpartitions.so文件分区.c'。在

^{pr2}$

下面是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)

Tags: 函数代码test语言foriflibint
1条回答
网友
1楼 · 发布于 2024-05-29 03:20:03

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

objdump -d -M intel <file name>

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

你可以尝试不同的编译器来比较结果。我已经检查了GCC5.4和Clang6.0。在gcc5.4中,Python脚本运行得更快,而使用Clang时,C程序运行得更快。在

相关问题 更多 >

    热门问题