首页 \ 问答 \ 时间与“假设”规则相对应(Timing vs the “as-if” rule)

时间与“假设”规则相对应(Timing vs the “as-if” rule)

关于“as-if”规则有一个很好的问题 ,但是我想知道在测量时间方面是否有任何重复。

考虑一下(从这里略微修改):

using std::chrono;
auto begin = steady_clock::now();

auto result = some_lengthy_calculation(some_params);

auto end= std::chrono::steady_clock::now();

std::cout << "Time diff = " << duration_cast<microseconds>(end - begin).count() <<std::endl;
std::cout << "Result = " << result;

允许编译器应用任何导致相同result优化。 这里的要点是“as-if”规则不直接适用于测量时间。 当然,在应用优化时,测量的时间不应该是恒定的。

所以我的问题是:当根据“as-if”规则允许编译器将其重新排列为以下之一时,如何使用上述代码可靠地测量时间?

auto temp = some_lengthy_calculation(some_params); // clever "optimization", precompute some stuff

auto begin = steady_clock::now();
auto result = temp;               // yay, I can use it here to pretend to be faster
auto end = steady_clock::now();

std::cout << "Time diff = " << duration_cast<microseconds>(end - begin).count() <<std::endl;
std::cout << "Result = " << result;

甚至“更优化”:

std::cout << "Time diff = " << 42 <<std::endl;
std::cout << "Result = " << some_lengthy_calculation(some_params);

我假设没有理智的编译器会这样做,但究竟是什么阻止了编译器进行这样的“优化”?

TL; DR ...

  • 可以观察优化和非优化代码之间的运行时差异
  • 如果允许编译器优化影响测量时间,那么是什么阻止了编译器根本不创建任何代码?

There is a great question about the "as-if" rule in general, but I wonder if there are any excpetions when it comes to measuring time.

Consider this (taken from here slightly modified):

using std::chrono;
auto begin = steady_clock::now();

auto result = some_lengthy_calculation(some_params);

auto end= std::chrono::steady_clock::now();

std::cout << "Time diff = " << duration_cast<microseconds>(end - begin).count() <<std::endl;
std::cout << "Result = " << result;

The compiler is allowed to apply any optimization that results in the same result. The point here is that the "as-if" rule does not apply to the measured time directly. Of course the measured time is not something that should be constant when optimizations are applied.

So my question is: How is it possible that I can reliably measure time with the above code when, according to the "as-if" rule, the compiler is allowed to rearrange it to one of the following?

auto temp = some_lengthy_calculation(some_params); // clever "optimization", precompute some stuff

auto begin = steady_clock::now();
auto result = temp;               // yay, I can use it here to pretend to be faster
auto end = steady_clock::now();

std::cout << "Time diff = " << duration_cast<microseconds>(end - begin).count() <<std::endl;
std::cout << "Result = " << result;

or even "more optimized":

std::cout << "Time diff = " << 42 <<std::endl;
std::cout << "Result = " << some_lengthy_calculation(some_params);

I assume no sane compiler would do that, but what exactly prevents a compiler from doing such "optimization"?

TL;DR...

  • One can observe the runtime difference between optimized and non-optimized code
  • If compiler optimizations are allowed to effect measured times, what prevents the compiler from not creating any code for the timing at all?

原文:https://stackoverflow.com/questions/46572817
更新时间:2023-05-13 15:05

最满意答案

你认为这是一个好方法吗? 或者,......嗯,我可以使用NSUrlRequest访问Core Data吗?

没有。

还有一个问题,我可以使用NSURL访问文件系统,这与Web上的数据相同。 (对吗?)我的应用程序会将缓存版本与我的Web服务器上的数据版本进行比较,如果它已经过时,则检索新数据。 我的应用程序只能访问文件系统。 所有数据实际上都是HTML页面,包括脚本和图像。 而且,我想缓存它们。

是。

但你也可以更聪明。 而“更聪明”的意思是“马特加拉格尔”。 看看他在替换本地数据远程UIWebView请求时非常有趣的方法。


Is it, do you think, a good approach? Or,...hmm, can I access to Core Data using NSUrlRequest?

No.

One more question, I might access to file system using NSURL, which is the same as to data on the Web. (right?) My app would compare version of the cache with version of data on my web server, and if it's old, retrieve new data. and my app will access only to file system. All data are actually HTML pages including script, and images. And, I want to cache them.

Yes.

But you could also be more clever. And by "more clever" I mean "Matt Gallagher." Take a look at his very interesting approach in Substituting local data for remote UIWebView requests.

相关问答

更多
  • 免责声明:我是一位经验丰富的Objective-C开发人员,但对Swift来说却是一个新手。 我的答案将是面向目标的。 你有很多选择。 另一张海报建议使用Core Data,但除非你有复杂的信息需要保存,否则这可能有点过分。 核心数据是一个庞大而复杂的框架,具有陡峭的学习曲线。 它非常强大,但是在你能够流利地使用它之前,我希望能花一到两周的紧张学习。 最简单,最干净的方法通常是使用NSUserDefaults 。 它是一个Cocoa类,可以读取/写入应用程序沙箱中系统维护文件的键/值对。 (基本上是一个自动 ...
  • 你应该使用writeToFile:options:error:而不是writeToFile:atomically: ; 这将给你一个应该证明有用的错误信息。 (相当于atomically:YES是选项常量NSDataWritingAtomic 。)确保返回的值为YES ; 如果没有,则应设置错误。 如果您获得的值为NO但未设置错误,则表示您的消息nil 。 Objective-C的一个怪癖是消息传递nil完全有效。 如果定义方法返回某个东西,你甚至会得到一个结果: 0或等价( NO , nil等) 在这种情 ...
  • 嘿,存储和管理数据的最佳方式是核心数据框架,您可以在官方文档中阅读它。 Hey, the best way to store and manage data is Core Data framework, you can read about it in official docs.
  • 为了最大限度地减少委托方法调用所花费的时间,您应该找到一个在游戏中保存有意义的地方(完成级别,检查点等)。 您还可以向应用程序委托中添加一个新的委托方法,当您的应用程序转换到后台时,将调用该方法,您可以复制以前在applicationWillTerminate: 。 要实现的新委托方法是-applicationDidEnterBackground: . 您还将收到一条通知,告知用户切换回您的应用程序,作为applicationWillEnterForeground: . To minimize the am ...
  • 最简单的选择是将这些值以键值对的形式保存到NSUserDefaults中。 NSUserDefaults *stdDefaults = [NSUserDefaults standardUserDefaults]; if([stdDefaults objectForKey:@"APP_OPENED"] == FALSE) { [stdDefaults setValue:@"YOUR_VALUE" forKey:@"YOUR_KEY"]; //Store more val ...
  • 这可能是因为它被暂停(多任务处理)。 您可以在plist文件中禁用多任务处理: 将UIApplicationExitsOnSuspend设置为NO/false (未选中) 这会完全禁用多任务处理。 或者,您可以实现新的应用程序委托,这些委托会在恢复时重新启动并重新加载您的数据: - (void)applicationWillEnterForeground:(UIApplication *)application That's probably because it just got suspended ( ...
  • 我为此使用NSUserDefaults。 首先检查用户是否第一次打开应用程序,然后检查NSUserDefault的第一个对象的值 //defaults is a object of NSUserDefault NSString *URLEntered =[defaults objectForKey:@"URLISENTERED"]; if (!URLEntered) { [defaults setValue:@"0" forKey:@"URLISENTERED"]; } U ...
  • 有一个紧密的解决方案 使用Apple推送通知服务:它允许您发送带有消息的警报和用户打开应用程序的按钮,它还可以为您的应用程序图标添加编号徽章(想想whatsapp,mail) 。 这是一个解释如何使用它的链接http://www.raywenderlich.com/3443/apple-push-notification-services-tutorial-part-12 这是你可以得到的最接近的,如果用户没有打开应用程序你就无法使用iphone做任何事情 there is a close solution ...
  • 如果您使用的是xib,则可以在app delegate applicationDidFinishLaunchingWithOptions 。 创建一个全局BOOL并检查它在应用程序启动时的价值,例如: 。H @class ViewController; @class SecondViewController; @interface AppDelegate : UIResponder @property (strong, nonatomic) UIWindow ...
  • 你认为这是一个好方法吗? 或者,......嗯,我可以使用NSUrlRequest访问Core Data吗? 没有。 还有一个问题,我可以使用NSURL访问文件系统,这与Web上的数据相同。 (对吗?)我的应用程序会将缓存版本与我的Web服务器上的数据版本进行比较,如果它已经过时,则检索新数据。 我的应用程序只能访问文件系统。 所有数据实际上都是HTML页面,包括脚本和图像。 而且,我想缓存它们。 是。 但你也可以更聪明。 而“更聪明”的意思是“马特加拉格尔”。 看看他在替换本地数据远程UIWebView请 ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)