簡體   English   中英

用於簡單導入語句的 python 代碼比編譯的 C 代碼快一個數量級

[英]python code order of magnitude faster than compiled C code for simple import statement

我對以下兩個語義等效(?)程序的性能差異感到困惑。

Python:

#test.py
import time
starttime=time.time()
import tensorflow 
print(f"Import took: {time.time() - starttime}")

C 使用 CPython

//test.c
#include <Python.h>
#include <stdio.h> 
#include <time.h> 
int main(int argc, char *argv[])
{
    Py_Initialize();
    clock_t t = clock();
    PyObject* pModule = PyImport_ImportModule("tensorflow");
    double time_taken = ((double)clock() - t)/CLOCKS_PER_SEC;
    printf("Import took:  %f\n", time_taken);
    return 0;
}

現在比較兩者:

cl.exe /I"C:\Program Files\Python37\include" test.c
link test.obj python37.lib /LIBPATH:"C:\Program Files\Python37\libs"
.\test.exe

2020-04-17 13:00:51.598550:W tensorflow/stream_executor/platform/default/dso_loader.cc:55] 無法加載動態庫“cudart64_100.dll”; dlerror: cudart64_100.dll not found 2020-04-17 13:00:51.606296: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.

進口拍:23.160523891448975

python test.py

2020-04-17 13:01:19.525648:W tensorflow/stream_executor/platform/default/dso_loader.cc:55] 無法加載動態庫“cudart64_100.dll”; dlerror: cudart64_100.dll not found 2020-04-17 13:01:19.530726: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.

進口拍:2.3172824382781982

沒關系,但我的 tensorflow 版本是 1.15 為什么 python VM 代碼比編譯的 CPython 代碼快得多? python vm 是否添加了 PyImport_ImportModule 沒有的一些魔力?

PyImport_ImportModule 是 C ABI 的一部分,這意味着它可能會受到性能損失: https://docs.python.org/3/chtml-list/stable-abi-list/stable-abi。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM