Created
May 14, 2021 14:19
-
-
Save TotallyNotChase/8f23f9ecf6e417b0e9f5abec9d2734c7 to your computer and use it in GitHub Desktop.
Benching iterables against normal arrays - https://github.com/TotallyNotChase/c-iterators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "iterator.h" | |
#include "maybe.h" | |
#include "typeclass.h" | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <inttypes.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <sys/types.h> | |
#define CLOCK_PRECISION 1000000000L | |
static inline int64_t diffnsec(struct timespec *timeA_p, struct timespec *timeB_p) | |
{ | |
return ((timeA_p->tv_sec * CLOCK_PRECISION) + timeA_p->tv_nsec) - | |
((timeB_p->tv_sec * CLOCK_PRECISION) + timeB_p->tv_nsec); | |
} | |
DefineMaybe(size_t) | |
DefineIteratorOf(size_t); | |
typedef struct | |
{ | |
size_t i; | |
size_t const size; | |
size_t const *const srcarr; | |
} SzArrIter; | |
static Maybe(size_t) szarrnxt(SzArrIter *self) | |
{ | |
return self->i < self->size ? Just(self->srcarr[self->i++], size_t) : Nothing(size_t); | |
} | |
static impl_iterator(SzArrIter *, size_t, szarriter_to_itrble, szarrnxt) | |
#define ARRSZ 1000000 | |
void sumarr(void) | |
{ | |
/* Generate an array of random elements */ | |
size_t arr[ARRSZ]; | |
for (size_t i = 0; i < ARRSZ; i++) | |
{ | |
arr[i] = rand() % 1000; | |
} | |
/* Sum the array */ | |
struct timespec start = {0}, end = {0}; | |
size_t sum = 0; | |
clock_gettime(CLOCK_MONOTONIC, &start); | |
for (size_t i = 0; i < ARRSZ; i++) | |
{ | |
sum += arr[i]; | |
} | |
clock_gettime(CLOCK_MONOTONIC, &end); | |
printf("Sum of array: %zd\n", sum); | |
printf("Time taken for summing array: %" PRIi64 "ns \n", diffnsec(&end, &start)); | |
} | |
void sumit(void) | |
{ | |
/* Generate an array of random elements */ | |
size_t arr[ARRSZ]; | |
for (size_t i = 0; i < ARRSZ; i++) | |
{ | |
arr[i] = rand() % 1000; | |
} | |
/* Turn array into an iterable */ | |
Iterable(size_t) arrit = szarriter_to_itrble(&(SzArrIter){.i = 0, .size = ARRSZ, .srcarr = arr}); | |
/* Sum the array */ | |
struct timespec start = {0}, end = {0}; | |
size_t sum = 0; | |
clock_gettime(CLOCK_MONOTONIC, &start); | |
Maybe(size_t) res = arrit.tc->next(arrit.self); | |
for (size_t x = from_just_(res); is_just(res); res = arrit.tc->next(arrit.self), x = from_just_(res)) | |
{ | |
sum += x; | |
} | |
clock_gettime(CLOCK_MONOTONIC, &end); | |
printf("Sum of iterable: %zd\n", sum); | |
printf("Time taken for summing iterable: %" PRIi64 "ns \n", diffnsec(&end, &start)); | |
} | |
int main(void) | |
{ | |
srand(time(NULL)); | |
sumarr(); | |
sumit(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment