我正在使用Boost Graph库对Dijkstra算法进行基准测试,我意识到我代码中的某些函数的执行时间比我将其拆分的连续部分的执行时间总和大得多。 :
Part 1: 0.521417
Part 2: 0.000022
Part 3: 0.543387
Whole: 2.283262
下面是代码。要考虑的函数是test_dijkstra
函数。数据集文件为here(60 MB)。
#include <memory>
#include <chrono>
#include <unistd.h>
#include <boost/config.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
using namespace std;
using namespace boost;
using std::chrono::steady_clock;
using namespace std::chrono;
typedef adjacency_list < listS, vecS, undirectedS,
no_property, property < edge_weight_t, int > > graph_t;
typedef graph_traits < graph_t >::vertex_descriptor vertex_descriptor;
typedef pair<int, int> Edge;
typedef struct Data
{
int n, m;
int src;
vector<Edge> edges;
vector<int> weights;
} Data;
void print_elapsed_time(steady_clock::time_point start, steady_clock::time_point end)
{
double elapsedSeconds = ((end - start).count()) * steady_clock::period::num / static_cast<double>(steady_clock::period::den);
printf("%lf\n", elapsedSeconds);
}
auto capture()
{
FILE *dataset=fopen("test_6000.in", "r");
auto pdata=make_unique<Data>();
int m, n, src;
fscanf(dataset,"%d %d %d", &n, &m, &src);
pdata->n=n;
pdata->m=m;
pdata->src=src;
for (int i=0; i<m; i++)
{
int a, b, w;
fscanf(dataset,"%d %d %d", &a, &b, &w);
(pdata->edges).push_back(make_pair(a, b));
(pdata->weights).push_back(w);
}
return pdata;
}
void test_dijkstra(Edge *edge_array, int *weights, int n, int m, int src)
{
auto start1 = steady_clock::now();
graph_t g(edge_array, edge_array + m, weights, n);
auto end1 = steady_clock::now();
printf("Part 1: ");
print_elapsed_time(start1, end1);
auto start2 = steady_clock::now();
vector<vertex_descriptor> p(num_vertices(g));
vector<int> d(num_vertices(g));
vertex_descriptor s = vertex(src, g);
auto end2 = steady_clock::now();
printf("Part 2: ");
print_elapsed_time(start2, end2);
auto start3 = steady_clock::now();
dijkstra_shortest_paths(g, s, predecessor_map(&p[0]).distance_map(&d[0]));
auto end3 = steady_clock::now();
printf("Part 3: ");
print_elapsed_time(start3, end3);
}
int main (void)
{
auto pdata=capture();
auto data=*pdata;
auto edges=data.edges;
auto weights=data.weights;
auto pedges=&edges[0];
auto pweights=&weights[0];
int n, m, src;
n=data.n;
m=data.m;
src=data.src;
auto start = steady_clock::now();
test_dijkstra(pedges, pweights, n, m, src);
auto end = steady_clock::now();
printf("Whole: ");
print_elapsed_time(start, end);
return 0;
}
有人可以解释这个“悖论”吗?