【发布时间】:2017-08-01 15:16:57
【问题描述】:
我正在尝试评估在这两种情况下对每个元素进行操作的链表循环之间的时间差:
1) 在函数内部进行操作
2) 在同一个地方没有函数调用的情况下进行操作
我原以为函数调用的变化会因为每次调用创建和销毁堆栈帧的操作系统开销而变得更加昂贵,但我得到的结果恰恰相反。我不明白为什么。有人可以解释发生了什么吗?
这是我的程序:
// ConsoleApplication4.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include<iostream>
#include<chrono>
#include<stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
class linked_list_node
{
int a;
public :
std::string var;
bool eval()
{
if (var == "abc")
return true;
return false;
}
linked_list_node() { a = rand() % 100; if (a % 2 == 0) var = "abc"; }
linked_list_node* nxt;
std::string getVar() { return var; }
linked_list_node* getNext()
{
return nxt;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
linked_list_node *head = new linked_list_node();
linked_list_node *trav = head;
int len = 75000;
while (len != 0)
{
linked_list_node *n = new linked_list_node();
trav->nxt = n;
trav = n;
len--;
}
trav->nxt = NULL;
//traversal with function
int length = 0;
trav = head;
std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now();
while (trav != NULL)
{
length++;
if (trav->eval())
std::cout << "";
trav = trav->nxt;
}
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << "Time difference with function == " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << std::endl;
//traversal without function
trav = head;
length = 0;
begin = std::chrono::steady_clock::now();
while (trav != NULL)
{
length++;
if (trav->var =="abc")
std::cout << "";
trav = trav->nxt;
}
end = std::chrono::steady_clock::now();
std::cout << "Time difference without function = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << std::endl;
getchar();
return 0;
}
这些是我的结果:
与函数的时差 == 18100
无函数时差 = 33700000
【问题讨论】: