qsort is a sorting function in the C language standard library. Its performance (that is, its running speed) mainly depends on the number of comparisons and exchanges of elements. The number of comparisons and exchanges of elements depends mainly on the size and distribution of the input array.
The following is an example of a simple qsort performance test. You can copy this code and run it to see the results:
#include <stdio.h> #include <stdlib.h> #include <time.h> // 定义一个比较函数,用于 qsort int compare(const void* a, const void* b) { return (*(int*)a - *(int*)b); } int main() { // 生成一个随机数组 srand(time(0)); int n = 1000000; // 数组大小,你可以根据需要调整这个数值 int* arr = (int*)malloc(n * sizeof(int)); for(int i = 0; i < n; i++) { arr[i] = rand(); } // 记录开始时间 clock_t start = clock(); // 使用 qsort 对数组进行排序 qsort(arr, n, sizeof(int), compare); // 记录结束时间 clock_t end = clock(); // 输出运行时间(以毫秒为单位) printf("Sorting %d elements took %f milliseconds\n", n, ((double)end - start) * 1000 / CLOCKS_PER_SEC); // 释放内存 free(arr); return 0; }
Please note that this test is only to provide an approximate performance indicator , does not guarantee the same results in all cases. Actual performance will be affected by many factors, including hardware performance, operating system scheduling, memory access patterns, etc. If you need more precise performance testing, you may need to use specialized performance analysis tools such as gprof, Valgrind's callgrind, kcachegrind, etc.
The above is the detailed content of C language qsort function algorithm performance test. For more information, please follow other related articles on the PHP Chinese website!