我有一个简单的程序来测量浮点乘法(以及随机生成,编译g++ -O0)。
在主机(Ubuntu 16.04)上运行时,每10000000次乘法给出〜1.6s,在镜像“ubuntu”中的容器中运行(不重新编译)时,给出〜3.6s。
有人可以解释为什么它慢了〜2.5倍吗?
ps我有多次运行程序来消除异常值。我不需要对其进行优化,只需对其发生的详细说明即可。
测试文件
#include <cstdio>
#include <math.h>
#include <chrono>
using namespace std;
using namespace std::chrono;
// timer cribbed from
// https://gist.github.com/gongzhitaao/7062087
class Timer
{
public:
Timer() : beg_(clock_::now()) {}
void reset() { beg_ = clock_::now(); }
double elapsed() const
{
return duration_cast<second_>(clock_::now() - beg_).count();
}
private:
typedef high_resolution_clock clock_;
typedef duration<double, ratio<1>> second_;
time_point<clock_> beg_;
};
#define randf() ((double)rand()) / ((double)(RAND_MAX))
double warmup(Timer tmr) {
tmr.reset();
for (int i = 0; i < 100000000; i++)
{
double r1 = randf();
double r2 = randf();
}
double elapsed = tmr.elapsed();
return elapsed;
}
double test(Timer tmr) {
double total = 0.0;
tmr.reset();
for (int i = 0; i < 100000000; i++)
{
double r1 = randf();
double r2 = randf();
total += r1*r2;
}
double elapsed = tmr.elapsed();
return elapsed;
}
double avg(double* arr) {
double res = 0.0;
for (int i = 0; i < 10; i++) {
res += *(arr + i);
}
return res / 10;
}
int main()
{
double total;
int total2;
Timer tmr;
double warmup_runs[10];
for (int i = 0; i < 10; i++)
{
warmup_runs[i] = warmup(tmr);
printf("warm - %f\n", warmup_runs[i]);
}
double avg_warmup = avg(warmup_runs);
printf("avg warm - %f\n", avg_warmup);
const int runs = 10;
double result[runs];
for (int i = 0; i < runs; i++)
{
result[i] = test(tmr);
printf("real - %f\n", result[i]);
}
double avg_result = avg(result);
printf("avg real - %f\n", avg_result);
printf("d - %f\n", avg_result - avg_warmup);
}
Docker文件FROM ubuntu
WORKDIR /arythmetics
COPY a.out .
编译g++ -O0 test.cpp
在构建后使用的容器中运行:docker run -it <container> .bin/bash
.\a.out
更新:使用
-static
标志进行编译后,两种环境下的程序运行时间相同还有另一个问题,为什么实际上是相同的?是否应该有一些容器化开销?
最佳答案
您正在从libc调用rand
函数,该函数可能在Docker容器中以不同的方式实现。
为了获得可靠的结果,请在主机和容器中使用完全相同的OS和软件包版本,或者使用类似以下内容的静态链接libc:
g++ -O0 -static-libstdc++ -static-libgcc test.cpp
关于linux - 为什么Docker中的算术运算会变慢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63754636/