用插入排序验证线程进行随机和最坏排序, 以及非线程的随机和最坏排序的时间差距
/*************************************************************************> File Name: t.cpp> Author: Function_Dou> Mail:> Created Time: 2018年02月07日 星期三 18时51分14秒************************************************************************/#include <stdio.h>#include <pthread.h>#include "apue.h"#include <sys/time.h>const int Max = 30000;const int max = Max - 1;long arr[Max];long arr1[Max];void Sort(long *arr, int num){int i, j, t;for (i = 0; i < max; i++)for(j = i + 1; j < Max; j++)if(num == 0){if(arr[i] < arr[j]){t = arr[i];arr[i] = arr[j];arr[j] = t;}}elseif(arr[i] > arr[j]){t = arr[i];arr[i] = arr[j];arr[j] = t;}}void *SortThread(void *){Sort(arr, 0);pthread_exit((void *)1);}void *SortThread2(void *){Sort(arr1, 1);pthread_exit((void *)1);}int main(void){int i;struct timeval start, end;// 线程开始的计时gettimeofday(&start, NULL);// 生成大量随机数, 用于排序srandom(1);for(i = 0; i < Max; i++){arr[i] = random();arr1[i] = i;}// 一个进行随机排序. 一个最坏情况的排序pthread_t threadid1, threadid2;pthread_create(&threadid1, NULL, SortThread, NULL);pthread_create(&threadid2, NULL, SortThread, NULL);// 线程的结束时间gettimeofday(&end, NULL);// 时间的差值计算printf("pthread no time is : %.4f\n", (double)(end.tv_sec * 1000000 + end.tv_usec - (start.tv_sec * 1000000 - start.tv_usec)) / 1000000);// ------------------------------------// 没有线程的排序计时gettimeofday(&start, NULL);for(i = 0; i < Max; i++)arr[i] = random();// 一个进行随机排序. 一个最坏情况的排序Sort(arr, 0);Sort(arr1, 1);// 线程的结束时间gettimeofday(&end, NULL);// 时间的差值计算printf("pthread no time is : %.4f\n", (double)(end.tv_sec * 1000000 + end.tv_usec - (start.tv_sec * 1000000 - start.tv_usec)) / 1000000);exit(0);}
几次运行结果 :
[root@localhost Pthread]# ./a.outpthread no time is : 2.0003pthread no time is : 3.7875[root@localhost Pthread]# ./a.outpthread no time is : 0.4818pthread no time is : 4.2071[root@localhost Pthread]# ./a.outpthread no time is : 1.4883pthread no time is : 5.2815[root@localhost Pthread]# ./a.outpthread no time is : 0.9232pthread no time is : 4.6768
当我将 Sort(arr1, 1) 注释掉后, 运行的结果, 有线程的结果偏小可能是我电脑关掉了些不必要的东西造成的吧. 可以看出, 无线程的排序变化并不大
[root@localhost Pthread]# ./a.outpthread no time is : 0.7061pthread no time is : 3.5253[root@localhost Pthread]# ./a.outpthread no time is : 0.4698pthread no time is : 3.4451[root@localhost Pthread]# ./a.outpthread no time is : 1.8373pthread no time is : 4.7519[root@localhost Pthread]# ./a.outpthread no time is : 0.6393pthread no time is : 3.3885

本文通过使用插入排序算法,在有线程和无线程的情况下分别对随机数据和最坏情况进行排序,对比了两种方式下的时间消耗,展示了线程在排序任务中的效率影响。
1873

被折叠的 条评论
为什么被折叠?



