Skip to content

Instantly share code, notes, and snippets.

@Youka
Last active August 29, 2015 14:07
Show Gist options
  • Select an option

  • Save Youka/b6f43faedc968dee0de6 to your computer and use it in GitHub Desktop.

Select an option

Save Youka/b6f43faedc968dee0de6 to your computer and use it in GitHub Desktop.
2d data are dirty
#include <stdint.h> // uint8_t, uint16_t, uintptr_t
#include <string.h> // memset
// Data are dirty?
int is_dirty_naive(const uint16_t width, const uint16_t height, const uint16_t stride, const uint8_t* data){
for(uint16_t row = 0; row < height; ++row){
for(uint16_t col = 0; col < width; ++col)
if(data[col] > 0)
return 1;
data += stride;
}
return 0;
}
int is_dirty_optimized(const uint16_t width, const uint16_t height, const uint16_t stride, const uint8_t* data){
const uint8_t* data_end = data + height * stride,
*row_end;
const uint16_t offset = stride - width;
while(data < data_end){
row_end = data + width;
while(data < row_end)
if(*data++)
return 1;
data += offset;
}
return 0;
}
int is_dirty_more_optimized(const uint16_t width, const uint16_t height, const uint16_t stride, const uint8_t* data){
const uint8_t* data_end = data + height * stride,
*row_end;
const uintptr_t* dataX,
*rowX_end;
const uint16_t offset = stride - width,
widthX = width / sizeof(uintptr_t);
const uint8_t widthX_rest = width % sizeof(uintptr_t);
while(data < data_end){
rowX_end = (dataX = (uintptr_t*)data) + widthX;
while(dataX < rowX_end)
if(*dataX++)
return 1;
row_end = (data = (uint8_t*)dataX) + widthX_rest;
while(data < row_end)
if(*data++)
return 1;
data += offset;
}
return 0;
}
// Program entry
int main(){
// 2D data
const uint16_t width = 1200, height = 720, stride = width + 100;
uint8_t data[height * stride];
memset(data, 0, sizeof(data));
// Test is_dirty_* call performance
for(int i=0; i < 1000; ++i){
is_dirty_naive(width, height, stride, data);
is_dirty_optimized(width, height, stride, data);
is_dirty_more_optimized(width, height, stride, data);
}
// Program finish successful
return 0;
}
/*
gcc -pg -std=c99 -c main.c -o main.o
g++ -o test main.o -pg -lgmon
------------------------------------
Each sample counts as 0.01 seconds.
% cumulative self self total
time seconds seconds calls ms/call ms/call name
50.28 4.55 4.55 1000 4.55 4.55 is_dirty_naive
39.01 8.08 3.53 1000 3.53 3.53 is_dirty_optimized
10.61 9.04 0.96 1000 0.96 0.96 is_dirty_more_optimized
0.11 9.05 0.01 __chkstk_ms
*/
@Youka
Copy link
Author

Youka commented Oct 12, 2014

This was tested with a x86 compiler.
With a x64 compiler, is_dirty_more_optimized would be even faster because of bigger registers to use for comparison.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment