Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active August 21, 2022 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/2105d2f5bced792571833588e82fbab4 to your computer and use it in GitHub Desktop.
Save louisswarren/2105d2f5bced792571833588e82fbab4 to your computer and use it in GitHub Desktop.
CPython testing
*.o
*.o
primes.*.so
PYTHON = python
CPYARCH = $(shell $(PYTHON) -c \
'import sys;i=sys.implementation;print(i.cache_tag+"-"+i._multiarch)')
PYTHONLIB = python$(shell $(PYTHON) --version | cut -d' ' -f2 | cut -d'.' -f1,2)
# Warnings
CFLAGS += -Wno-unused-result -Wsign-compare -Wall -Wformat -Werror=format-security
# Debugging
CFLAGS += -DNDEBUG -g
# Optimisation
CFLAGS += -fwrapv -O3 -march=x86-64 -mtune=generic -fno-plt -flto=auto -ffat-lto-objects
LDFLAGS += -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now -flto=auto
# Build flags
CFLAGS += -pipe
# Hardening
CFLAGS += -Wp,-D_FORTIFY_SOURCE=2 -fstack-clash-protection -fcf-protection
.PHONY: run
run: primestest.py primes.$(CPYARCH).so
$(PYTHON) $<
primes.$(CPYARCH).so: primesmodule.o primes.o
$(CC) -shared $(LDFLAGS) $^ -o $@
primesmodule.o: primesmodule.c primes.h
$(CC) $(CFLAGS) -fPIC -I/usr/include/$(PYTHONLIB) -c $< -o $@
primes.o: primes.c primes.h
.PHONY: clean
clean:
rm -f *.o *.so
#include <math.h>
#include "primes.h"
int
is_prime(int n)
{
int bound;
if (n < 2 || (n > 2 && n % 2 == 0))
return 0;
bound = sqrt(n);
for (int i = 3; i <= bound; i += 2) {
if (n % i == 0)
return 0;
}
return 1;
}
int is_prime(int n);
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "primes.h"
static PyObject *
primes_is_prime(PyObject *self, PyObject *args)
{
int n;
if (!PyArg_ParseTuple(args, "i", &n))
return NULL;
if (is_prime(n)) {
Py_INCREF(Py_True);
return Py_True;
} else {
Py_INCREF(Py_False);
return Py_False;
}
}
static PyMethodDef PrimesMethods[] = {
{"is_prime", primes_is_prime, METH_VARARGS, "Prime test"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef primesmodule = {
PyModuleDef_HEAD_INIT,
"primes",
NULL,
-1,
PrimesMethods
};
PyMODINIT_FUNC
PyInit_primes(void)
{
return PyModule_Create(&primesmodule);
}
import primes
for i in range(1, 21):
print(i, primes.is_prime(i), sep = "\t")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment