---
title: "C++如何计算代码运行时间"
author: "foxcoder"
date: "2014-01-03T23:32:32Z"
tags: []
categories: ["编程语言"]
slug: "c"
draft: false
lastmod: "2014-01-03T23:32:32Z"
id: 1998887
url: "https://foxcoder.iteye.com/blog/1998887"
---

```
#include<iostream>
#include<ctime>
using namespace std;
void main()
{
	//统计运行时间精确到秒
	time_t tstart, tend;
	long i=1000000000000;
	tstart=time(0);
	while(i--);
	tend=time(0);
	cout<<difftime(tend,tstart)<<endl;
	//统计运行时间精确到毫秒
	i=1000000000000;
	double tstart1, tend1;
	tstart1 = clock();
	while(i--);
	tend1 = clock();
	cout<<(tend1-tstart1)/CLOCKS_PER_SEC<<endl;
}
```

 

话不多说，直接看代码和运行结果截图。

![](http://dl2.iteye.com/upload/attachment/0092/8087/83ff8755-3d4e-3909-be58-6692cfc2656a.jpg)