I want to convert a days-since-last-activity value in my SQL Server stored procedure to a logarithmic representation for weighted ordering (alongside other criteria) of the matching search results before truncating them. Log2 approximates my needs pretty well and seems like something that should be very efficient.
CAST (LOG(lastActivityAge)/LOG(2)) AS TINYINT
Would work fine, but it seems extremely wasteful to ask my server to do such heavy lifting just to get the highest set bit position.
Any suggestions on a more efficient way to do this?
There are some bit twiddling hacks to find the highest bit but they cannot be expressed easily in T-SQL (requiring loops). UDF’s are out of questions for performance reasons.
You can go a little bit faster with Denali:
Or hard-code the
LOG(2)expression as I’m not sure the optimizer can constant-fold it away. Anyway, you need millions of rows to notice the difference.One last trick: If there are some very common values, try this: