C語言qsort函數演算法效能測試,qsort效能測試

來源:互聯網
上載者:User

C語言qsort函數演算法效能測試,qsort效能測試

對於演算法的複雜度,一種直觀感測方式是測量一定數量級資料的演算法已耗用時間。

以C語言提供的qsort為例子,以100萬資料量測試其計算時間,可感知O(nlg(n))的時間代價:

C代碼如下:

#include <stdio.h>#include <stdlib.h>#include <time.h>#define N 1000000//int (*Comp)(const void *,const void *)int compare(const void *p1, const void *p2) {return *(float*)p1 > *(float*)p2;}int main(){float x[N];srand( time(NULL) );clock_t t1 = clock();for(int j = 0; j < 10; j++) {for(long i = 0; i < N; i++)x[i] = (float)rand()/RAND_MAX;qsort(x, N, sizeof(float), compare);}for(int i = 0; i < 10; i++)printf("%f ", x[i]);printf("\n");clock_t t2 = clock();printf("浮點數排序演算法用時:%f 秒\n", (double)(t2 - t1)/ CLOCKS_PER_SEC);return 0;}

在筆記本上用gcc qsort_test.c編譯和運行,10次100萬資料隨機產生和排序用時結果為:

~/tmp$ ./a.out
0.000000 0.000001 0.000001 0.000002 0.000002 0.000004 0.000004 0.000005 0.000006 0.000006
浮點數排序演算法用時:2.236941 秒

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.