David Marec 8 hónapja
szülő
commit
1329ca1107
2 módosított fájl, 127 hozzáadás és 0 törlés
  1. 73 0
      dummy/max.c
  2. 54 0
      dummy/popcount.c

+ 73 - 0
dummy/max.c

@@ -0,0 +1,73 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <time.h>
+#include <string.h>
+
+static int pile[256];
+static int pileQ[256];
+static int pileR[256];
+
+#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))
+
+__attribute__((pure)) static int compare(const void * restrict p1, const void * restrict p2) 
+{
+	int left	= *(const int *)p1;
+	int right	= *(const int *)p2;
+
+	return (left > right) ? 1 : (left == right) ? 0 : -1;
+}
+
+static int is_equal(const int * restrict p1, const int * restrict p2, size_t n)
+{
+	while (n--) {
+		if (*p1 != *p2)
+			return -1;
+
+		++p1;
+		++p2;
+	}
+
+	return 0;
+}
+
+static int get_max(const int *p1, size_t n)
+{
+	int max = *p1;
+
+	--n;
+	++p1;
+	while (n--) {
+		if (max < *p1)
+			max = *p1;
+		++p1;
+	}
+
+	return max;
+}
+
+int main()
+{
+	arc4random_buf(pile, sizeof(pile));
+	clock_t tq0, tq1;
+
+	memcpy(pileQ, pile, sizeof pileQ);
+	memcpy(pileR, pile, sizeof pileR);
+	qsort(&pileQ, ARRAY_SIZE(pileQ), sizeof(*pileQ), compare);
+	heapsort(&pileR, ARRAY_SIZE(pileR), sizeof(*pileR), compare); 
+
+	fputs("000: ", stdout);
+	for (size_t k =	0; k < ARRAY_SIZE(pileQ); ) {
+		printf("%16d ", pileQ[k]);
+		++k;
+		if (!(k % 8)) {
+			puts("");
+			printf("%03zu: ", k);
+		}
+	}
+	puts("");
+
+
+	printf("sort: %s.\n", is_equal(pileR, pileQ, ARRAY_SIZE(pile)) ? "KO" : "OK");
+	printf("Max : %d.\n", get_max(pile, ARRAY_SIZE(pile)));
+	return 0;
+}

+ 54 - 0
dummy/popcount.c

@@ -0,0 +1,54 @@
+#include <stdio.h>
+#include <stdlib.h>
+
+static __attribute__((pure)) int popcount(int v)
+{
+	if (__builtin_expect ( v != 0, 1)) {
+
+		int c = 0;
+
+		while (v) {
+			if (v & 1)
+				++c;
+			v>>=1;
+		}
+		return c;
+	}
+	return 0;
+}
+
+static __attribute__((pure)) int ctz(int v)
+{
+	if (__builtin_expect ( v != 0, 1)) {
+		int c = 0;
+		while (1) {
+			if((v & 1))
+				break;
+			++c;
+			v>>=1;
+		}
+		return c;
+	}
+	return sizeof v * 8;
+}
+
+#define TEST(f0, f1, x) { int r0 = f0(x); int r1=f1(x); \
+	printf("[%-3s] C ==> %d vs ASM ==> %d.\n", (r0==r1) ? "OK":"BUG", r0, r1) ; }
+
+int main(int argc, char *argv[])
+{
+	int v;
+
+	if (argc != 2)
+		return 1;
+
+	v = strtol(argv[1], NULL, 16);
+
+	printf("Pop count: ");
+	TEST(popcount, __builtin_popcount, v)
+
+	printf("CTZ      : ");
+	TEST(ctz, __builtin_ctz, v)
+
+	return 0;
+}