欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

clock()

程序员文章站 2024-01-23 19:57:58
...

·clock()计时函数
  clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t。在MSDN中,查得对clock函数定义如下:clock_t clock(void) ;简单而言,就是该程序从启动到函数调用占用CPU的时间。这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数。

·例子:

// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include<ctime>
using namespace std;

struct ListNode {
	int m_nValue;
	ListNode *m_pNext;
};

// pHead指向第一个node
void AddToTail(ListNode * &pHead, const int &value) {
	ListNode* pNew = new ListNode();
	pNew->m_nValue = value;
	pNew->m_pNext = NULL;

	if (pHead == NULL) {
		pHead = pNew;
	}
	else {
		ListNode *pNode = pHead;
		while (pNode->m_pNext != NULL) {
			pNode = pNode->m_pNext;
		}

		pNode->m_pNext = pNew;
	}
}

void AddToTail2(ListNode **pHead, const int &value) {
	ListNode* pNew = new ListNode();
	pNew->m_nValue = value;
	pNew->m_pNext = NULL;

	if (*pHead == NULL) {
		*pHead = pNew;
	}
	else {
		ListNode *pNode = *pHead;
		while (pNode->m_pNext != NULL) {
			pNode = pNode->m_pNext;
		}

		pNode->m_pNext = pNew;
	}
}


//void RemoveNode(ListNode **pHead, int value)

int main()
{
	ListNode *pHead = NULL;
	ListNode *pHead2 = NULL; 
	clock_t startTime, endTime;

	startTime = clock();
	for (int i = 0; i < 10000*10; i++) {
		AddToTail(pHead, i);
	}
	endTime = clock();
	cout << endTime - startTime << endl;

	startTime = clock();
	for (int i = 0; i < 10000*10; i++) {
		AddToTail2(&pHead2, i);
	}
	endTime = clock();
	cout << (double)(endTime - startTime)/CLOCKS_PER_SEC << endl;

	/*
	while (pHead != NULL) {
		cout << pHead->m_nValue << endl;
		pHead = pHead->m_pNext;
	}

	while (pHead2 != NULL) {
		cout << pHead2->m_nValue << endl;
		pHead2 = pHead2->m_pNext;
	}*/
	
    return 0;
}


相关标签: c++ clock