README.md
1# FXdiv
2
3[![MIT License](https://img.shields.io/badge/License-MIT%20License-blue.svg)](https://github.com/Maratyszcza/FXdiv/blob/master/LICENSE)
4[![Build Status](https://img.shields.io/travis/Maratyszcza/FXdiv.svg)](https://travis-ci.org/Maratyszcza/FXdiv)
5
6
7Header-only library for division via fixed-point multiplication by inverse
8
9On modern CPUs and GPUs integer division is several times slower than multiplication. FXdiv implements an algorithm to replace an integer division with a multiplication and two shifts. This algorithm improves performance when an application performs repeated divisions by the same divisor.
10
11## Features
12
13- Integer division for `uint32_t`, `uint64_t`, and `size_t`
14- Header-only library, no installation or build required
15- Compatible with C99, C++, OpenCL, and CUDA
16- Uses platform-specific compiler intrinsics for optimal performance
17- Covered with unit tests and microbenchmarks
18
19## Example
20
21```c
22#include <fxdiv.h>
23
24/* Division of array by a constant: reference implementation */
25void divide_array_c(size_t length, uint32_t array[], uint32_t divisor) {
26 for (size_t i = 0; i < length; i++) {
27 array[i] /= divisor;
28 }
29}
30
31/* Division of array by a constant: implementation with FXdiv */
32void divide_array_fxdiv(size_t length, uint32_t array[], uint32_t divisor) {
33 const struct fxdiv_divisor_uint32_t precomputed_divisor =
34 fxdiv_init_uint32_t(divisor);
35 for (size_t i = 0; i < length; i++) {
36 array[i] = fxdiv_quotient_uint32_t(array[i], precomputed_divisor);
37 }
38}
39```
40
41## Status
42
43Project is in alpha stage. API is unstable. Currently working features:
44
45| Platform | uint32_t | uint64_t | size_t |
46| --------------- |:--------:|:--------:|:--------:|
47| x86-64 gcc | Works | Works | Works |
48| x86-64 MSVC | Works | Works | Works |
49| x86 gcc | Works | Works | Works |
50| x86 MSVC | Works | Works | Works |
51| ARMv7 gcc | Works | Works | Works |
52| PPC64 gcc | Works | Works | Works |
53| PNaCl clang | Works | Works | Works |
54| Asm.js clang | Works | Works | Works |
55| CUDA | Untested | Untested | Untested |
56| OpenCL | Untested | Untested | Untested |
57
58## References
59
60- Granlund, Torbjörn, and Peter L. Montgomery. "Division by invariant integers using multiplication." In ACM SIGPLAN Notices, vol. 29, no. 6, pp. 61-72. ACM, 1994. Available: [gmplib.org/~tege/divcnst-pldi94.pdf](https://gmplib.org/~tege/divcnst-pldi94.pdf)
61