---
title: 'This week in #dev (May 5, 2023)'
teaser: 'This week we''re talking about correctly measuring elapsed time and secret
  Active Record methods.

  '
tags: this week in dev,til,ruby,ruby on rails
author: thoughtbot
published_on: 2023-05-25
---

Welcome to another edition of This Week in #dev, a series of posts where we
bring some of the most interesting Slack conversations to the public.

## Measuring Elapsed Time Correctly

Sara Jackson learned about [`Process::CLOCK_MONOTONIC`]. It should be used
instead of system time updates when measuring elapsed time because it ensures
that the measurement is accurate and not affected by system time updates.

```rb
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
do_something(args)
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)

puts "Elapsed time: #{end_time - start_time}"
```

[`Process::CLOCK_MONOTONIC`]: https://docs.ruby-lang.org/en/3.2/Process.html#CLOCK_MONOTONIC

## Secret Active Record Methods

Summer ☀️ shares a cool Active Record feature: using `!` query methods to modify
a query object in place instead of returning a new one. Let's use `distinct!` as
an example:

```rb
# distinct! modifies the current query object, while distinct creates a new query object:
my_query = User.all
my_query.distinct!
my_query.to_sql
#=> "SELECT DISTINCT \"users\".* FROM \"users\""

my_query = User.all
my_other_query = my_query.distinct
my_query.to_sql
#=> "SELECT \"users\".* FROM \"users\""
my_other_query.to_sql
#=> "SELECT DISTINCT \"users\".* FROM \"users\""
```

In fact, `distinct` is implemented by calling [something similar] to
`self.dup.distinct!`, Summer ☀️ adds. This kind of pattern also exists for other
Active Record query methods like `where`/`where!`, `order`/`order!`,
`joins`/`joins!`, etc.

<aside class="warn">
  <p>
    <a href="https://thoughtbot.com/blog/authors/sean-doyle">Sean Doyle</a>
    points out that this is a private API and should not be depended upon in
    applications or gems.
  </p>
</aside>

[something similar]: https://github.com/rails/rails/blob/v6.1.7/activerecord/lib/active_record/relation/query_methods.rb#L921-L923

## Thanks

This edition was brought to you by: [Sara Jackson], [Sean Doyle] and [Summer ☀️]. Thanks to all contributors! 🎉

[Sara Jackson]: https://thoughtbot.com/blog/authors/sara-jackson
[Sean Doyle]: https://thoughtbot.com/blog/authors/sean-doyle
[Summer ☀️]: https://thoughtbot.com/blog/authors/summer
