java中要生产随机数的 话 直接 new一个 Random就 可以 了 ,c语言中的话会稍微麻烦一点点。

计算运行时间 在比较算法运行效率中 要 用到 。


#include<stdio.h> #include <stdlib.h> #include <time.h>   int main() { 	clock_t start, finish; //声明start和finish是两个时间 	srand(10); 	double time; //定义运行时间 	start = clock(); //获取开始时间 	printf("生成150000个随机数:\n"); 	for (int i=0; i<150000; i++) 	{    	 printf("%d ", rand()%100); 	} 	finish=clock(); 	printf("\n"); 	//time = (double)(finish - start); 	time = (double)(finish - start) / CLOCKS_PER_SEC;  	printf( "RunningTime:\n%f 秒\n",time);//显示  }

运行 结果 :

C语言中生产随机数及计算运行时间(微秒级)_算法


当程序运行时间非常短的时候,上面的方法往往无法捕捉到运行的时间,下面的方法可以让程序记录运行时间的方法精确到微秒。

#include<stdio.h> #include <stdlib.h> #include <time.h>   #include <sys/time.h> int main() { 	struct timeval tpstart,tpend;     	int timeuse; 	srand(10); 	printf("生成150000个随机数:\n"); 	//获得初始时间 	gettimeofday(&tpstart,NULL); 	for (int i=0; i<150000; i++) 	{    	 printf("%d ", rand()%100); 	} 	//获取结束时间 	gettimeofday(&tpend,NULL); 	printf("\n"); 	//计算耗时 	timeuse=1000000*(tpend.tv_sec-tpstart.tv_sec)+tpend.tv_usec-tpstart.tv_usec; 	printf( "RunningTime:\n%d微秒\n",timeuse);  }

其中

 struct timeval {
          time_t       tv_sec;     /* seconds */
          suseconds_t   tv_usec; /* microseconds */
    };

其中对tv_usec的说明为时间的毫秒部分。 而在实际中,该函数以及Linux内核返回的timeval
类型的时间值,tv_usec代表的是微秒精度(10的-6次方秒)。

这样就能够更加精确地去计算运行时间了:0)。