随性由我–C#

Linex’s Home

Apr
29

C# 中的高性能计时器

Posted by 上来下去

[奥地利]Daniel Strigl 著  野比 译

来源:http://www.codeproject.com

下载:
源文件

简介
精确的时间计量方法在某些应用程序中是非常重要的。常用的 Windows API 方法 GetTickCount() 返回系统启动后经过的毫秒数。另一方面,GetTickCount() 函数仅有 1ms 的分辨精度,很不精确。

故而,我们要另外寻找一种方法来精确测量时间。

Win32 API 使用 QueryPerformanceCounter() QueryPerformanceFrequency() 方法支持高精度计时。这些方法,比“标准的”毫秒精度的计时方法如 GetTickCount() 之类有高得多的精度。另一方面来说,在 C# 中使用“非托管”的 API 函数会有一定的开销,但比起使用一点都不精确的 GetTickCount() API 函数来说要好得多了。

第一个函数 QueryPerformanceCounter() 查询任意时刻高精度计数器的实际值。第二个函数 QueryPerformanceFrequency() 返回高精度计数器每秒的计数值。为了获得某一代码段经历的时间,你需要获得代码段开始前和结束后这两个计时时刻的高精度计数器实际值。这两个值的差指出了代码段执行所经历的时间。

然后通过将差除以每秒计数值(高精度计时器频率),就可以计算经过的时间了。

duration = (stop - start) / frequency
经过时间 = (停止时间 - 开始时间) / 频率

需要关于 QueryPerformanceCounter 和 QueryPerformanceFrequency 的更多信息,请参阅 MSDN 文档。

代码
下面的类实现了 QueryPerformanceCounter() QueryPerformanceFrequency() API 函数的功能。

复制内容到剪贴板

代码:

using System;
using System.Runtime.InteropServices;
using System.ComponentModel;
using System.Threading;

namespace Win32
{
    internal class HiPerfTimer
    {
        [DllImport(”Kernel32.dll”)]
        private static extern bool QueryPerformanceCounter(
            out long lpPerformanceCount);

        [DllImport(”Kernel32.dll”)]
        private static extern bool QueryPerformanceFrequency(
            out long lpFrequency);

        private long startTime, stopTime;
        private long freq;

        // 构造函数
        public HiPerfTimer()
        {
            startTime = 0;
            stopTime  = 0;

            if (QueryPerformanceFrequency(out freq) == false)
            {
                // 不支持高性能计数器
                throw new Win32Exception();
            }
        }

        // 开始计时器
        public void Start()
        {
            // 来让等待线程工作
            Thread.Sleep(0);

            QueryPerformanceCounter(out startTime);
        }

        // 停止计时器
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }

        // 返回计时器经过时间(单位:秒)
        public double Duration
        {
            get
            {
                return (double)(stopTime - startTime) / (double) freq;
            }
        }
    }
}

使用这个类很简单。只需要创建一个 HiPerfTimer 的实例,然后调用 Start() 开始计时,Stop() 停止计时。要获得经过的时间,调用 Duration() 函数即可。

参考下面的例子。

复制内容到剪贴板

代码:

HiPerfTimer pt = new HiPerfTimer();     // 创建新的 HiPerfTimer 对象
pt.Start();                             // 启动计时器
Console.WriteLine(”Test\n”);            // 需要计时的代码
pt.Stop();                              // 停止计时器
Console.WriteLine(”Duration: {0} sec\n”,
     pt.Duration); // 打印需要计时部分代码的用时

Jan
12

当点击ListView的列头时,对ListView排序

Posted by 上来下去

Jan
05

把datagridview的数据输出为Excel,Word的简单应用

Posted by 上来下去

public static void ExportData(DataGridView srcDgv,string fileName)//导出数据,传入一个datagridview和一个文件路径
{
string type = fileName.Substring(fileName.IndexOf(”.”)+1);//获得数据类型
if (type.Equals(”xls”,StringComparison.CurrentCultureIgnoreCase))//Excel文档
{
Excel.Application excel = new Excel.Application();
try
{
excel.DisplayAlerts = false;
excel.Workbooks.Add(true);
excel.Visible = false;

for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
{
excel.Cells[2, i+1] = srcDgv.Columns[i].HeaderText;
}

for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
{
for (int j = 0; j < srcDgv.Columns.Count; j++)
{
excel.Cells[i + 3, j + 1] = srcDgv[j, i].Value;
}
}

excel.Workbooks[1].SaveCopyAs(fileName);//保存
}
finally
{
excel.Quit();
}
return;
}

//保存Word文件

if (type.Equals(”doc”, StringComparison.CurrentCultureIgnoreCase))
{

object path = fileName;

Object none=System.Reflection.Missing.Value;
Word.Application wordApp = new Word.Application();
Word.Document document = wordApp.Documents.Add(ref none, ref none, ref none, ref none);
//建立表格
Word.Table table= document.Tables.Add(document.Paragraphs.Last.Range, srcDgv.Rows.Count+1, srcDgv.Columns.Count, ref none, ref none);

try
{

for (int i = 0; i < srcDgv.Columns.Count; i++)//设置标题
{
table.Cell(1, i + 1).Range.Text = srcDgv.Columns[i].HeaderText;
}

for (int i = 0; i < srcDgv.Rows.Count; i++)//填充数据
{
for (int j = 0; j < srcDgv.Columns.Count; j++)
{

table.Cell(i + 2, j + 1).Range.Text = srcDgv[j, i].Value.ToString();
}
}

document.SaveAs(ref path, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none, ref none);
document.Close(ref none, ref none, ref none);

}
finally
{
wordApp.Quit(ref none, ref none, ref none);
}

}

}

About Me

    About

    Some details about you.

    Open "about_text.txt" file in the theme folder to edit this text.

Recent Comments