From 286d4993d15d012c1bac08da142c93867508e11f Mon Sep 17 00:00:00 2001 From: qwang59 Date: Sun, 31 Mar 2024 16:05:55 +0800 Subject: [PATCH] Add sort_test.c for Intel PT case Signed-off-by: qwang59 --- pt/Makefile | 5 +++- pt/sort_test.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 pt/sort_test.c diff --git a/pt/Makefile b/pt/Makefile index c83ec5f9..e833399d 100644 --- a/pt/Makefile +++ b/pt/Makefile @@ -3,7 +3,7 @@ CC ?= "${CC}" -g -Wall CFLAGS += -DMAINLINE -I./ -BIN = cpl branch psb nonroot_test negative_test +BIN = cpl branch psb nonroot_test negative_test sort_test LFLAGS = -L./ -lipt @@ -25,5 +25,8 @@ nonroot_test: negative_test: $(CC) -o $@ $@.c utils.c ${CFLAGS} ${LFLAGS} +sort_test: + $(CC) -o $@ $@.c utils.c ${CFLAGS} ${LFLAGS} + clean: rm -rf $(BIN) *.o diff --git a/pt/sort_test.c b/pt/sort_test.c new file mode 100644 index 00000000..962e0dc5 --- /dev/null +++ b/pt/sort_test.c @@ -0,0 +1,74 @@ +#include +#include +#include + +#define ARRAY_LEN 3000 + +size_t partition(int *a, size_t low, size_t high); // Move the declaration of the partition function here + +static inline void start(struct timeval *tm) +{ + gettimeofday(tm, NULL); +} + +void swap(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} + +static inline void stop(struct timeval *tm1, struct timeval *tm2) +{ + unsigned long long t = 1000 * (tm2->tv_sec - tm1->tv_sec) + + (tm2->tv_usec - tm1->tv_usec) / 1000; + printf("%llu ms\n", t); +} + +size_t partition(int *a, size_t low, size_t high) +{ + int pivot = a[high]; + size_t i = low - 1; + + for (size_t j = low; j <= high - 1; j++) + { + if (a[j] < pivot) + { + i++; + swap(&a[i], &a[j]); + } + } + swap(&a[i + 1], &a[high]); + return (i + 1); +} + +void quick_sort(int *a, size_t low, size_t high) +{ + if (low < high) + { + size_t pivot = partition(a, low, high); + quick_sort(a, low, pivot - 1); + quick_sort(a, pivot + 1, high); + } +} + +void sort_array() +{ + printf("Quick sorting array of %zu elements\n", ARRAY_LEN); + int data[ARRAY_LEN]; + for (size_t i = 0; i < ARRAY_LEN; ++i) + { + data[i] = rand(); + } + quick_sort(data, 0, ARRAY_LEN - 1); +} + +int main() +{ + struct timeval tm1, tm2; + start(&tm1); + sort_array(); + gettimeofday(&tm2, NULL); + stop(&tm1, &tm2); + return 0; +}