Home Backend Development Python Tutorial Introduction to how to use ctypes to improve Python's execution speed

Introduction to how to use ctypes to improve Python's execution speed

Mar 28, 2017 pm 02:59 PM

This article introduces how to use ctypes to improve the execution speed of Python, and has certain reference value for everyone to learn to use python. Friends in need come and take a look.

">

Preface

ctypes is Python's external function library. It provides C-compatible data types and allows calling dynamic link libraries/shared libraries. Function. It can wrap these libraries for use in Python. This interface introduced into the C language can help us do many things, such as some small problems that need to call C code to improve performance. Through it, you can access the Windows system. kernel32.dll and msvcrt.dll dynamic link libraries, as well as the libc.so.6 library on Linux systems. Of course, you can also use your own compiled shared library

Let’s look at a simple example first. Use Python to find prime numbers within 1000000, repeat this process 10 times, and calculate the running time

import math
from timeit import timeit
def check_prime(x):
values ​​= xrange(2 , int(math.sqrt(x)) + 1)
for i in values:
if x % i == 0:
return False
return True
def get_prime(n) :
return [x for x in xrange(2, n) if check_prime(x)]
print timeit(stmt='get_prime(1000000)', setup='from __main__ import get_prime',
number =10)

Output

42.8259568214

Write a check_prime function in C language below, and then import it as a shared library (dynamic link library)

#include
#include
int check_prime(int a)
{
int c;
for ( c = 2 ; c <= sqrt(a) ; c++ ) {
if ( a%c == 0 )
return 0;
}
return 1;
}

Use The following command generates a .so (shared object) file

gcc -shared -o prime.so -fPIC prime.c
import ctypes
import math
from timeit import timeit
check_prime_in_c = ctypes.CDLL('./prime.so').check_prime
def check_prime_in_py(x):
values ​​= xrange(2, int(math.sqrt(x)) + 1)
for i in values:
if x % i == 0:
return False
return True
def get_prime_in_c(n):
return [x for x in xrange(2, n) if check_prime_in_c( x)]
def get_prime_in_py(n):
return [x for x in xrange(2, n) if check_prime_in_py(x)]
py_time = timeit(stmt='get_prime_in_py(1000000)', setup ='from __main__ import get_prime_in_py',
number=10)
c_time = timeit(stmt='get_prime_in_c(1000000)', setup='from __main__ import get_prime_in_c',
number=10)
print "Python version: {} seconds".format(py_time)
print "C version: {} seconds".format(c_time)

Output

Python version: 43.4539749622 seconds
C version: 8.56250786781 seconds

We can see the obvious performance gap. Here are more ways to determine whether a number is prime

Let’s look at a more complicated example of quick sort.

mylib.c

#include
typedef struct _Range {
 int start, end;
} Range;
Range new_Range(int s, int e) {
 Range r;
 r.start = s;
 r.end = e;
 return r;
}
void swap(int *x, int *y) {
 int t = *x;
 *x = *y;
 *y = t;
}
void quick_sort(int arr[], const int len) {
 if (len <= 0)
   return;
 Range r[len];
 int p = 0;
 r[p++] = new_Range(0, len - 1);
 while (p) {
   Range range = r[--p];
   if (range.start >= range.end)
     continue;
   int mid = arr[range.end];
   int left = range.start, right = range.end - 1;
   while (left < right) {
     while (arr[left] < mid && left < right)
       left++;
     while (arr[right] >= mid && left < right)
       right--;
     swap(&arr[left], &arr[right]);
   }
   if (arr[left] >= arr[range.end])
     swap(&arr[left], &arr[range.end]);
   else
     left++;
   r[p++] = new_Range(range.start, left - 1);
   r[p++] = new_Range(left + 1, range.end);
 }
}
gcc -shared -o mylib.so -fPIC mylib.c

使用ctypes有一个麻烦点的地方是原生的C代码使用的类型可能跟Python不能明确的对应上来。比如这里什么是Python中的数组?列表?还是 array 模块中的一个数组。所以我们需要进行转换

test.py

import ctypes
import time
import random
quick_sort = ctypes.CDLL('./mylib.so').quick_sort
nums = []
for _ in range(100):
 r = [random.randrange(1, 100000000) for x in xrange(100000)]
 arr = (ctypes.c_int * len(r))(*r)
 nums.append((arr, len(r)))
init = time.clock()
for i in range(100):
 quick_sort(nums[i][0], nums[i][1])
print "%s" % (time.clock() - init)

输出

1.874907

与Python list 的 sort 方法进行对比

import ctypes
import time
import random
quick_sort = ctypes.CDLL('./mylib.so').quick_sort
nums = []
for _ in range(100):
 nums.append([random.randrange(1, 100000000) for x in xrange(100000)])
init = time.clock()
for i in range(100):
 nums[i].sort()
print "%s" % (time.clock() - init)

输出

2.501257

至于结构体,需要定义一个类,包含相应的字段和类型

class Point(ctypes.Structure):
 _fields_ = [('x', ctypes.c_double),
       ('y', ctypes.c_double)]

除了导入我们自己写的C语言扩展文件,我们还可以直接导入系统提供的库文件,比如linux下c标准库的实现 glibc

import time
import random
from ctypes import cdll
libc = cdll.LoadLibrary('libc.so.6') # Linux系统
# libc = cdll.msvcrt # Windows系统
init = time.clock()
randoms = [random.randrange(1, 100) for x in xrange(1000000)]
print "Python version: %s seconds" % (time.clock() - init)
init = time.clock()
randoms = [(libc.rand() % 100) for x in xrange(1000000)]
print "C version : %s seconds" % (time.clock() - init)

输出

Python version: 0.850172 seconds
C version : 0.27645 seconds

总结

以上就是这篇文章的全部内容,希望对大家学习或使用Python能有一定的帮助,如果有疑问大家可以留言交流。

The above is the detailed content of Introduction to how to use ctypes to improve Python's execution speed. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to Use Python to Find the Zipf Distribution of a Text File How to Use Python to Find the Zipf Distribution of a Text File Mar 05, 2025 am 09:58 AM

This tutorial demonstrates how to use Python to process the statistical concept of Zipf's law and demonstrates the efficiency of Python's reading and sorting large text files when processing the law. You may be wondering what the term Zipf distribution means. To understand this term, we first need to define Zipf's law. Don't worry, I'll try to simplify the instructions. Zipf's Law Zipf's law simply means: in a large natural language corpus, the most frequently occurring words appear about twice as frequently as the second frequent words, three times as the third frequent words, four times as the fourth frequent words, and so on. Let's look at an example. If you look at the Brown corpus in American English, you will notice that the most frequent word is "th

How Do I Use Beautiful Soup to Parse HTML? How Do I Use Beautiful Soup to Parse HTML? Mar 10, 2025 pm 06:54 PM

This article explains how to use Beautiful Soup, a Python library, to parse HTML. It details common methods like find(), find_all(), select(), and get_text() for data extraction, handling of diverse HTML structures and errors, and alternatives (Sel

Image Filtering in Python Image Filtering in Python Mar 03, 2025 am 09:44 AM

Dealing with noisy images is a common problem, especially with mobile phone or low-resolution camera photos. This tutorial explores image filtering techniques in Python using OpenCV to tackle this issue. Image Filtering: A Powerful Tool Image filter

How to Work With PDF Documents Using Python How to Work With PDF Documents Using Python Mar 02, 2025 am 09:54 AM

PDF files are popular for their cross-platform compatibility, with content and layout consistent across operating systems, reading devices and software. However, unlike Python processing plain text files, PDF files are binary files with more complex structures and contain elements such as fonts, colors, and images. Fortunately, it is not difficult to process PDF files with Python's external modules. This article will use the PyPDF2 module to demonstrate how to open a PDF file, print a page, and extract text. For the creation and editing of PDF files, please refer to another tutorial from me. Preparation The core lies in using external module PyPDF2. First, install it using pip: pip is P

How to Cache Using Redis in Django Applications How to Cache Using Redis in Django Applications Mar 02, 2025 am 10:10 AM

This tutorial demonstrates how to leverage Redis caching to boost the performance of Python applications, specifically within a Django framework. We'll cover Redis installation, Django configuration, and performance comparisons to highlight the bene

How to Perform Deep Learning with TensorFlow or PyTorch? How to Perform Deep Learning with TensorFlow or PyTorch? Mar 10, 2025 pm 06:52 PM

This article compares TensorFlow and PyTorch for deep learning. It details the steps involved: data preparation, model building, training, evaluation, and deployment. Key differences between the frameworks, particularly regarding computational grap

How to Implement Your Own Data Structure in Python How to Implement Your Own Data Structure in Python Mar 03, 2025 am 09:28 AM

This tutorial demonstrates creating a custom pipeline data structure in Python 3, leveraging classes and operator overloading for enhanced functionality. The pipeline's flexibility lies in its ability to apply a series of functions to a data set, ge

Introduction to Parallel and Concurrent Programming in Python Introduction to Parallel and Concurrent Programming in Python Mar 03, 2025 am 10:32 AM

Python, a favorite for data science and processing, offers a rich ecosystem for high-performance computing. However, parallel programming in Python presents unique challenges. This tutorial explores these challenges, focusing on the Global Interprete

See all articles