将浮点值分配给性能计数器

时间:2015-04-22 06:58:39

标签: c# performancecounter

我在C#中创建了一个性能计数器。但是,在为其分配值时,我希望该值为float而不是long,但我似乎无法弄清楚如何执行此操作。有人可以帮忙吗?

我使用的代码来自Counter of type RateOfCountsPerSecond32 always shows 0

public static void Test()
{
    var ccdc = new CounterCreationDataCollection();

    // Add the counter.
    const string counterName = "RateOfCountsPerSecond64Sample";
    var rateOfCounts64 = new CounterCreationData
    {
        CounterType = PerformanceCounterType.RateOfCountsPerSecond64,
        CounterName = counterName
    };
    ccdc.Add(rateOfCounts64);

    // Create the category.
    const string categoryName = "RateOfCountsPerSecond64SampleCategory";
    if (PerformanceCounterCategory.Exists(categoryName))
        PerformanceCounterCategory.Delete(categoryName);
    PerformanceCounterCategory.Create(categoryName, "",
        PerformanceCounterCategoryType.SingleInstance, ccdc);

    // create the counter
    var pc = new PerformanceCounter(categoryName, counterName, false);
    pc.RawValue = 1000; // <-- want to assign a float value here
}

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

嗯,你不能;数据类型为long。只需按比例缩放它(因此你可以保留几个小数位,例如低位数) - 例如x1000 - 并将其四舍五入:

pc.RawValue = (long)(value * 1000);

但是,由于您正在使用RateOfCountsPerSecond32 - 您应该记录总计,而不是费率。后端计算费率。