• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // FieldTrial is a class for handling details of statistical experiments
6 // performed by actual users in the field (i.e., in a shipped or beta product).
7 // All code is called exclusively on the UI thread currently.
8 //
9 // The simplest example is an experiment to see whether one of two options
10 // produces "better" results across our user population.  In that scenario, UMA
11 // data is uploaded to aggregate the test results, and this FieldTrial class
12 // manages the state of each such experiment (state == which option was
13 // pseudo-randomly selected).
14 //
15 // States are typically generated randomly, either based on a one time
16 // randomization (generated randomly once, and then persistently reused in the
17 // client during each future run of the program), or by a startup randomization
18 // (generated each time the application starts up, but held constant during the
19 // duration of the process), or by continuous randomization across a run (where
20 // the state can be recalculated again and again, many times during a process).
21 // Only startup randomization is implemented thus far.
22 
23 //------------------------------------------------------------------------------
24 // Example:  Suppose we have an experiment involving memory, such as determining
25 // the impact of some pruning algorithm.
26 // We assume that we already have a histogram of memory usage, such as:
27 
28 //   HISTOGRAM_COUNTS("Memory.RendererTotal", count);
29 
30 // Somewhere in main thread initialization code, we'd probably define an
31 // instance of a FieldTrial, with code such as:
32 
33 // // Note, FieldTrials are reference counted, and persist automagically until
34 // // process teardown, courtesy of their automatic registration in
35 // // FieldTrialList.
36 // scoped_refptr<FieldTrial> trial = new FieldTrial("MemoryExperiment", 1000);
37 // int group1 = trial->AppendGroup("_high_mem", 20);  // 2% in _high_mem group.
38 // int group2 = trial->AppendGroup("_low_mem", 20);   // 2% in _low_mem group.
39 // // Take action depending of which group we randomly land in.
40 // if (trial->group() == group1)
41 //   SetPruningAlgorithm(kType1);  // Sample setting of browser state.
42 // else if (trial->group() == group2)
43 //   SetPruningAlgorithm(kType2);  // Sample alternate setting.
44 
45 // We then modify any histograms we wish to correlate with our experiment to
46 // have slighly different names, depending on what group the trial instance
47 // happened (randomly) to be assigned to:
48 
49 // HISTOGRAM_COUNTS(FieldTrial::MakeName("Memory.RendererTotal",
50 //                                       "MemoryExperiment").data(), count);
51 
52 // The above code will create 3 distinct histograms, with each run of the
53 // application being assigned to of of the three groups, and for each group, the
54 // correspondingly named histogram will be populated:
55 
56 // Memory.RendererTotal            // 96% of users still fill this histogram.
57 // Memory.RendererTotal_high_mem   // 2% of users will fill this histogram.
58 // Memory.RendererTotal_low_mem    // 2% of users will fill this histogram.
59 
60 //------------------------------------------------------------------------------
61 
62 #ifndef BASE_FIELD_TRIAL_H_
63 #define BASE_FIELD_TRIAL_H_
64 
65 #include <map>
66 #include <string>
67 
68 #include "base/lock.h"
69 #include "base/ref_counted.h"
70 #include "base/time.h"
71 
72 
73 class FieldTrial : public base::RefCounted<FieldTrial> {
74  public:
75   typedef int Probability;  // Probability type for being selected in a trial.
76 
77   // A return value to indicate that a given instance has not yet had a group
78   // assignment (and hence is not yet participating in the trial).
79   static const int kNotParticipating;
80 
81   // Provide an easy way to assign all remaining probability to a group.  Note
82   // that this will force an instance to participate, and make it illegal to
83   // attempt to probabalistically add any other groups to the trial.  When doing
84   // A/B tests with timings, it is often best to define all groups, so that
85   // histograms will get unique names via the MakeName() methods.
86   static const Probability kAllRemainingProbability;
87 
88   // The name is used to register the instance with the FieldTrialList class,
89   // and can be used to find the trial (only one trial can be present for each
90   // name).
91   // Group probabilities that are later supplied must sum to less than or equal
92   // to the total_probability.
93   FieldTrial(const std::string& name, Probability total_probability);
94 
95   // Establish the name and probability of the next group in this trial.
96   // Sometimes, based on construction randomization, this call may causes the
97   // provided group to be *THE* group selected for use in this instance.
98   int AppendGroup(const std::string& name, Probability group_probability);
99 
100   // Return the name of the FieldTrial (excluding the group name).
name()101   std::string name() const { return name_; }
102 
103   // Return the randomly selected group number that was assigned.
104   // Return kNotParticipating if the instance is not participating in the
105   // experiment.
group()106   int group() const { return group_; }
107 
108   // If the field trial is not in an experiment, this returns the empty string.
109   // if the group's name is empty, a name of "_" concatenated with the group
110   // number is used as the group name.
group_name()111   std::string group_name() const { return group_name_; }
112 
113   // Helper function for the most common use: as an argument to specifiy the
114   // name of a HISTOGRAM.  Use the original histogram name as the name_prefix.
115   static std::string MakeName(const std::string& name_prefix,
116                               const std::string& trial_name);
117 
118  private:
119   friend class base::RefCounted<FieldTrial>;
120 
~FieldTrial()121   ~FieldTrial() {}
122 
123   // The name of the field trial, as can be found via the FieldTrialList.
124   // This is empty of the trial is not in the experiment.
125   const std::string name_;
126 
127   // The maximu sum of all probabilities supplied, which corresponds to 100%.
128   // This is the scaling factor used to adjust supplied probabilities.
129   Probability divisor_;
130 
131   // The randomly selected probability that is used to select a group (or have
132   // the instance not participate).  It is the product of divisor_ and a random
133   // number between [0, 1).
134   Probability random_;
135 
136   // Sum of the probabilities of all appended groups.
137   Probability accumulated_group_probability_;
138 
139   int next_group_number_;
140 
141   // The pseudo-randomly assigned group number.
142   // This is kNotParticipating if no group has been assigned.
143   int group_;
144 
145   // A textual name for the randomly selected group, including the Trial name.
146   // If this Trial is not a member of an group, this string is empty.
147   std::string group_name_;
148 
149   DISALLOW_COPY_AND_ASSIGN(FieldTrial);
150 };
151 
152 //------------------------------------------------------------------------------
153 // Class with a list of all active field trials.  A trial is active if it has
154 // been registered, which includes evaluating its state based on its probaility.
155 // Only one instance of this class exists.
156 class FieldTrialList {
157  public:
158   // Define a separator charactor to use when creating a persistent form of an
159   // instance.  This is intended for use as a command line argument, passed to a
160   // second process to mimic our state (i.e., provide the same group name).
161   static const char kPersistentStringSeparator;  // Currently a slash.
162 
163   // This singleton holds the global list of registered FieldTrials.
164   FieldTrialList();
165   // Destructor Release()'s references to all registered FieldTrial instances.
166   ~FieldTrialList();
167 
168   // Register() stores a pointer to the given trial in a global map.
169   // This method also AddRef's the indicated trial.
170   static void Register(FieldTrial* trial);
171 
172   // The Find() method can be used to test to see if a named Trial was already
173   // registered, or to retrieve a pointer to it from the global map.
174   static FieldTrial* Find(const std::string& name);
175 
176   static int FindValue(const std::string& name);
177 
178   static std::string FindFullName(const std::string& name);
179 
180   // Create a persistent representation of all FieldTrial instances for
181   // resurrection in another process.  This allows randomization to be done in
182   // one process, and secondary processes can by synchronized on the result.
183   // The resulting string contains only the names, the trial name, and a "/"
184   // separator.
185   static void StatesToString(std::string* output);
186 
187   // Use a previously generated state string (re: StatesToString()) augment the
188   // current list of field tests to include the supplied tests, and using a 100%
189   // probability for each test, force them to have the same group string.  This
190   // is commonly used in a sub-process, to carry randomly selected state in a
191   // parent process into this sub-process.
192   //  Currently only the group_name_ and name_ are restored.
193   static bool StringAugmentsState(const std::string& prior_state);
194 
195   // The time of construction of the global map is recorded in a static variable
196   // and is commonly used by experiments to identify the time since the start
197   // of the application.  In some experiments it may be useful to discount
198   // data that is gathered before the application has reached sufficient
199   // stability (example: most DLL have loaded, etc.)
application_start_time()200   static base::TimeTicks application_start_time() {
201     if (global_)
202       return global_->application_start_time_;
203     // For testing purposes only, or when we don't yet have a start time.
204     return base::TimeTicks::Now();
205   }
206 
207  private:
208   // Helper function should be called only while holding lock_.
209   FieldTrial* PreLockedFind(const std::string& name);
210 
211   // A map from FieldTrial names to the actual instances.
212   typedef std::map<std::string, FieldTrial*> RegistrationList;
213 
214   static FieldTrialList* global_;  // The singleton of this class.
215 
216   // This will tell us if there is an attempt to register a field trial without
217   // creating the FieldTrialList. This is not an error, unless a FieldTrialList
218   // is created after that.
219   static bool register_without_global_;
220 
221   // A helper value made availabel to users, that shows when the FieldTrialList
222   // was initialized.  Note that this is a singleton instance, and hence is a
223   // good approximation to the start of the process.
224   base::TimeTicks application_start_time_;
225 
226   // Lock for access to registered_.
227   Lock lock_;
228   RegistrationList registered_;
229 
230   DISALLOW_COPY_AND_ASSIGN(FieldTrialList);
231 };
232 
233 #endif  // BASE_FIELD_TRIAL_H_
234 
235