我创建了一个共享对象并从两个不同的程序访问它并测量时间。
DATA 数组是两个进程之间的共享对象。
情况1:在program1内使用while
程序1:
access shared DATA array ;// to load into memory and avoid page fault during access time calculation
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program1, Time1=%d\n",Time_needed);
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program1, Time2=%d\n",Time_needed);
while(1){}; // I replace this by sleep(1000) in CASE-2
程序2:
access shared DATA array ;// to load into memory and avoid page fault during access time calculation
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program2, Time1=%d\n",Time_needed);
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program2, Time1=%d\n",Time_needed);
输出:首先我运行program1,然后运行Program2
Inside Program1, Time1 = 17620
Inside Program1, Time1 = 17680
Inside Program2, Time1 = 7620
Inside Program2, Time1 = 7600
情况2:在program1内使用sleep()
程序1:
access shared DATA array ;// to load into memory and avoid page fault during access time calculation
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program1, Time1=%d\n",Time_needed);
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program1, Time2=%d\n",Time_needed);
sleep(1000);
程序2:
access shared DATA array ;// to load into memory and avoid page fault during access time calculation
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program2, Time1=%d\n",Time_needed);
start=timer;
access shared DATA array
end=timer;
Time_needed= end-start
printf("Inside Program2, Time1=%d\n",Time_needed);
输出:首先我运行program1,然后运行Program2
Inside Program1, Time1 = 17620
Inside Program1, Time1 = 17680
Inside Program2, Time1 = 17620
Inside Program2, Time1 = 17600
从情况 -1 的输出中,我可以说共享数据 DATA 数组 由第一个程序加载到内存/缓存中,第二个程序从缓存中访问它。而 CASE-2 也是如此,但结果看起来像是在 Program1 进入休眠状态时从缓存中清除的。
我在linux下使用GCC。
有什么线索吗?提前致谢 。
最佳答案
您没有准确描述如何运行不同版本(不同的进程?),但假设它们是连续的 - 您可能会看到 sleep() 的影响
这当然取决于具体的实现和硬件,但它很可能会让您的 CPU 进入某种省电/ sleep 状态(这就是它的设计目的)。如果是这种情况,那么核心缓存将必须作为该过程的一部分进行刷新,并且您将在冷缓存中醒来。另一方面,whie 循环的目的是在磨削 CPU 并保持其事件状态(以及缓存)的同时执行繁忙的等待循环,除非您碰巧在此过程中进行了上下文切换。
确切的细节再次取决于实现,在 x86 上,您可以使用内联汇编来调用 Monitor+mwait 指令,这些指令允许您指定想要实现的确切 C 状态深度。深度越深,关闭的缓存就越多(主要与 L3 相关)。
关于c - 使用 while() 和 sleep() 让程序进入休眠模式的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21676633/