Print time!

Introduction

关于Cpp知识点的结合练习。

Overview

本次练习涉及的知识点

vector的几种打印方式
将函数作为参数传入其他函数
精确[毫秒及微秒]时间的计量

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
#include <ctime>
#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

using namespace std;


// 几种打印vector的方法
void printvector1(vector<int> v){
for(int i=0; i<v.size(); i++){
// cout<< i;
cout << v[i]<<" ";
}
}

void printvector2(vector<int> v){
for (vector<int>::iterator iter = v.begin(); iter != v.end(); ++iter)
cout << *iter<< " ";
}

void printvector3(vector<int> v){
auto itr = v.begin();
while( itr != v.end()){
cout << *(itr++) <<" ";
}
}

// 将函数作为参数传入
typedef void (*pf)(vector<int> v);


// 精确时间的计量
int taketime(pf f, vector<int> v){
struct timeval start, end;

long mtime, seconds, useconds;

gettimeofday(&start, NULL);
printf("Elapsed time: %ld milliseconds\n", mtime);
for (int i=0; i<1000; i++)
f(v);
gettimeofday(&end, NULL);

seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
cout <<endl<< mtime;
return 0;
}

int main(){
vector<int> daysInMonth = {1,2,3,4,5,6,7,8,9,10,11,12};
taketime(printvector1, daysInMonth);
return 0;
}

Refrence

Data Structures and AlgorithmAnalysis in C++[p84]

击蒙御寇