c语言clock()计时函数(结果很精准)

版权声明:欢迎转载请注明转自方辰昱的博客https://blog.csdn.net/viafcccy https://blog.csdn.net/viafcccy/article/details/85255754

#include<stdio.h>
#include<time.h>
clock_t start, stop; //clock_t为clock()函数返回的变量类型
double duration;
int main()
{
    start=clock();
    //******************************
    //*这里写你所要测试运行时间的程序 * 
    //******************************
    stop=clock();
    duration=(double)(stop-start)/CLK_TCK; //CLK_TCK为clock()函数的时间单位,即时钟打点
    printf("%f\n",duration);
    return 0;
}

案例:
测试链表和数组的写入速度

链表:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

typedef struct student {
char num[20];   /*学号*/
char name[10];	/*姓名*/
char sex[5];	/*性别*/
int age;		/*年龄*/
int score;	/*平均成绩*/
student * next;
}student;

typedef struct HeadNode {
int length;
student * next0;
}HeadNode;
 
int input(HeadNode * headnode)
{
	int i;
	student * head = (student*)malloc(sizeof(student));
	student * tail = NULL;
	headnode->length = 0;
	strcpy(head->num,"8207181119");
	strcpy(head->name,"方辰昱");
	strcpy(head->sex,"男");
	head->age = 18;
	head->score = 100;
	if(headnode->length == 0)
	{
		headnode->next0 = head;
		headnode->length++;
	}
	for(i = 0;i < 1000000;i++)
	{
		tail = (student*)malloc(sizeof(student));
		strcpy(tail->num,"8207181119");
		strcpy(tail->name,"方辰昱");
		strcpy(tail->sex,"男");
		tail->age = 18;
		tail->score = 100;
		head->next = tail;
		head = tail;
		headnode->length++;
	}
	tail->next = NULL;
	return 0;
}

del(HeadNode * headnode)
{
	student * node1 = headnode->next0;
	student * node2 = headnode->next0;
	int i = 0;
	for(i = 0;i < headnode->length; i++)
	{
		node2 = node1->next;
		free(node1);
		node1 = node2;
	}
	free(headnode);
	headnode = NULL;
}

int main()
{
	clock_t start, stop;   
	start = clock();
	double duration;
	HeadNode * headnode = (HeadNode*)malloc(sizeof(HeadNode)); 	
	input(headnode);
	del(headnode);
    stop = clock();
	duration=(double)(stop-start)/CLK_TCK;
    printf("The time was: %f\n",duration);
	return 0;
}

数组:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

typedef struct student {
char num[20];   /*学号*/
char name[10];	/*姓名*/
char sex[5];	/*性别*/
int age;		/*年龄*/
int score;	/*平均成绩*/
}student;

student stu[1000000];

int input()
{
	int i;
	for(i = 0;i < 1000000;i++)
	{
		strcpy(stu[i].num,"8207181119");
		strcpy(stu[i].name,"方辰昱");
		strcpy(stu[i].sex,"男");
		stu[i].age = 18;
		stu[i].score = 100;
	}
	return 0;
}

int main()
{
	clock_t start, stop;   
	start = clock();
	double duration;
	input();
    stop = clock();
	duration=(double)(stop-start)/CLK_TCK;
    printf("The time was: %f\n",duration);
	return 0;
}

结果:

猜你喜欢

转载自blog.csdn.net/viafcccy/article/details/85255754
今日推荐