1. 程式人生 > >c語言clock()計時函式(結果很精準)

c語言clock()計時函式(結果很精準)


#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;
}

結果: