【发布时间】:2019-02-21 09:19:41
【问题描述】:
相信很多人都经历过。在 linux 上第一次执行 c++ 代码总是需要更长的时间。
就像在我的 linux 机器上第一次调用 ::clock_gettime(CLOCK_REALTIME, &ts); 比第三次慢五倍左右。
第一次分配内存比第二次慢 100 倍。
我尝试了预分配并在我的应用程序中使用了mlockall,但即便如此,一个函数的第一次执行比第二个慢大约 160 倍,比第三个慢大约两倍。
函数的伪代码如下。 msg 在堆上分配。但它不包括在时间测量中。 msg2 是 POD,所以在 slow_for_the_first_time 中根本没有内存分配。
void slow_for_the_first_time(Message * msg) {
Msg2 msg2;
//set msg2 using msg
.... }
只是想知道,什么可能导致第一次执行缓慢?有没有办法避免?
erenon 的回答很有帮助。我认为这可能是因为 Msg2 是在 so 库中定义的。
在使用 LD_BIND_NOW=1 之前,第一次执行时间约为 8000 纳秒,第二次约为 500 纳秒,第三次约为 200 纳秒。
现在第一个执行时间约为 2000 纳秒,而第二个和第三个保持不变。所以还是比第三次执行慢了10倍,应该还有其他因素影响第一次执行时间。
一些有趣的发现。
在slow_for_the_first_time之前调用下面的方法可以减少第一次执行时间1微秒
void dummySet(Msg2& msg2)
{
//set all fields of msg2. msg2 has about 30 fields it won't work if only set one field of msg2.
}
还有一点值得一提的是,第一次执行的慢肯定和msg无关,就像下面代码中的第二次slow_for_the_first_time
char buffer[sizeof(Message)];
memset(buffer, 0, sizeof(buffer));
slow_for_the_first_time((Message*)buffer);//calling the method with a dummy buffer.
.....
slow_for_the_first_time(msg);//calling the method for the second time with a real msg.
与下面代码中的第二个slow_for_the_first_time 一样快
slow_for_the_first_time(msg);//the first time takes around 2000 nanoseconds
.....
slow_for_the_first_time(msg);//the second time takes around 500 nanoseconds.
【问题讨论】: